TypedArray Subarray Shares The Same Buffer

subarray returns a view over the same ArrayBuffer so writes land in the source array, while slice copies bytes into independent memory.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
// TypedArray 的 subarray 是视图,slice 是拷贝:同一段 ArrayBuffer 上创建
const buffer = new ArrayBuffer(8);
const bytes = new Uint8Array(buffer);
bytes.set([10, 20, 30, 40, 50, 60, 70, 80]);

// subarray 共享底层内存:写入视图会落回原数组
const view = bytes.subarray(2, 5);
view[0] = 99;
console.log('after subarray write, bytes[2]:', bytes[2]);

// slice 复制出独立内存:改动不影响原数组
const copy = bytes.slice(2, 5);
copy[0] = 0;
console.log('after slice write, bytes[2]:', bytes[2]);
console.log('view contents:', [...view]);
console.log('copy contents:', [...copy]);

console.log('buffer byteLength:', buffer.byteLength);
console.log('view.buffer is the same object:', view.buffer === buffer);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

after subarray write, bytes[2]: 99
after slice write, bytes[2]: 99
view contents: [ 99, 40, 50 ]
copy contents: [ 0, 40, 50 ]
buffer byteLength: 8
view.buffer is the same object: true

How it works

All three arrays live on the same 8-byte ArrayBuffer: bytes spans all of it, and bytes.subarray(2, 5) returns a view overlaying bytes 2 through 4. Writing view[0] = 99 therefore mutates the underlying buffer — the follow-up read of bytes[2] prints 99, proving no copy happened. slice(2, 5) allocates its own storage instead, so zeroing copy[0] leaves bytes[2] untouched at 99. The identity check view.buffer === buffer states the sharing explicitly, and buffer.byteLength stays 8 because neither subarray nor slice resizes the original allocation.

What to watch for

  • Runs with what the toolchain already gives you — nothing extra.

The line that does the heavy lifting:

bytes.set([10, 20, 30, 40, 50, 60, 70, 80]);

The second piece of the puzzle:

const bytes = new Uint8Array(buffer);

To complete the picture:

const buffer = new ArrayBuffer(8);

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit.