Memory overhead of typed arrays and strings

I am trying to reduce memory usage in a javascript web application that stores a lot of information in memory in the form of a lot of small lines. When I changed the code to use Uint8Arrayinstead String, I noticed that memory usage increased.

For example, consider the following code that creates many small lines:

// (1000000 strings) x (10 characters)
var a=[];
for (let i=0; i<1000000; i++)
    a.push("a".repeat(10).toUpperCase());

If you put it on a blank page and allow the memory to be used for a few seconds, it will be set to 70 MiB in Google Chrome. The following code, on the other hand:

// (1000000 arrays) x (10 bytes)
var a=[];
for (let i=0; i<1000000; i++)
    a.push(new Uint8Array(10));

uses 233 MiB of memory. A blank page without code uses about 20 MiB. On the other hand, if I create a small number of large lines / arrays, the difference becomes smaller, and in the case of a single line / array with 10,000,000 characters / records, the memory usage is almost identical.

So why do typed arrays have such a large memory overhead?

+4
source share
2 answers

V8 . : Uint8Array, . TypedArrays ; TypedArrays .

.

:

, 16 .

Uint8Array :

  • ( )
  • (. )
  • (. )
  • ( )
  • # 1
  • # 2

  • :

  • buffer: ( )
  • buffer: (. )
  • :
  • :
  • :
  • :
  • : - ( )
  • : # 1
  • : # 2

  • :

  • : ()
  • : ( )
  • :
  • :

, , , 16 .

5 * 8 = 40 , 26 * 8 = 208 . ; , TypedArrays ( ArrayBuffers, JavaScript WebGL - ..).

( " " " " - , GC .)

+4

.

, . - .

, , , . , .

:

var a = [];                       for (let i=0; i<1000000; i++) a.push("1");
var b = new Uint8Array(10000000); for (let i=0; i<1000000; i++) a[i] = 1;
// 'b' is more memory efficient than 'a', just pay the price of Uint8Array one time
// and save the wasted memory in string allocation overhead 
+1

Source: https://habr.com/ru/post/1684146/


All Articles