3

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);
2
  • Or is a new memory space reserved when you resize it? From MDN: You can assign a new size to a resizable ArrayBuffer with a resize() call. New bytes are initialized to 0. Commented Sep 2, 2023 at 20:02
  • My main question is, is the full maxByteLength reserved up front? Commented Sep 2, 2023 at 20:12

1 Answer 1

3

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().

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Is there any documentation online that explains this?
@grandinero See the spec / implementation guidelines: tc39.es/ecma262/multipage/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.