Search code examples
javascriptarraybuffer

Memory allocated for resizeable Javascript ArrayBuffer


When you initialize an ArrayBuffer with maxByteLength to make it resizeable, are maxByteLength bytes reserved in memory up front so that the ArrayBuffer can grow in contiguous memory space?

Or is a new memory space reserved when you resize it? If so, are the bytes from the original ArrayBuffer copied over, or does the ArrayBuffer maintain references to multiple non-contiguous regions?

Code example to explain the situation I'm talking about:

const a = new ArrayBuffer(4, { maxByteLength: 8 });
new Uint32Array(a)[0] = 1024;
/* Will the ArrayBuffer grow within the initially
allocated memory region here,
will it reserve 4 more bytes somewhere else,
or will it reserve 8 bytes somewhere else and copy
over the existing data? */
a.resize(8);

Solution

  • No, the full maxByteLength is not reserved up front when creating a resizable ArrayBuffer. Only the initial byte length (4 in this case) is allocated.

    When you call resize(), a new ArrayBuffer will be allocated with the new size. The contents of the original buffer are then copied over to the new one.

    So in your example, first 4 bytes are allocated. When resize(8) is called, a new 8 byte buffer is allocated, and the original 4 bytes are copied over.

    The ArrayBuffer does not maintain references to multiple regions - resize() handles creating a new contiguous buffer and copying data over.

    So the maxByteLength just defines the upper bound that you can resize to. The actual memory usage grows as needed when calling resize().