Sub topic 10
Moving Instead of Copying: The transfer Option
This chapter assumes you already know how structuredClone makes deep copies and which types it supports, including ArrayBuffer and typed arrays such as Uint8Array. You should also be comfortable with try/catch and running code in Node.js or a browser console.
Why moving can beat copying
By default, structuredClone copies every byte of an ArrayBuffer. For a few kilobytes this costs almost nothing. For a 200 MB video frame or audio buffer, the copy doubles memory use and takes real time.
The transfer option gives you a different deal. You list buffers whose memory should be handed over to the result instead of duplicated. The result takes ownership of the memory, and the original buffer becomes detached. A detached buffer is an ArrayBuffer that no longer owns any memory. Its byteLength is 0, and you can no longer read from it or write to it.
The basic call
The second argument to structuredClone is an options object. Its transfer property is an array of transferable objects.
const buffer = new ArrayBuffer(8);
const moved = structuredClone(buffer, { transfer: [buffer] });
console.log(moved.byteLength); // 8
console.log(buffer.byteLength); // 0 (the original is now detached)The value you clone and the list of things you transfer are separate. The value can be any cloneable structure. The transfer list says which buffers inside that structure should be moved rather than copied.
Transferring the buffer behind a typed array
In real code you usually hold a typed array, not a bare buffer. A typed array is a view over an ArrayBuffer, and you transfer that buffer through the view's .buffer property. The view itself is cloned as a new view over the moved memory.
const bytes = new Uint8Array([1, 2, 3, 4]);
const message = { kind: 'chunk', payload: bytes };
const result = structuredClone(message, { transfer: [bytes.buffer] });
console.log(result.payload); // Uint8Array(4) [ 1, 2, 3, 4 ]
console.log(result.payload instanceof Uint8Array); // true
console.log(bytes.length); // 0
console.log(bytes.byteLength); // 0
console.log(message.payload === bytes); // true, but it is now emptyThe original object message still exists and still points at bytes. However, bytes now sits on a detached buffer, so it reports a length of 0 and contains no elements. Any other view over the same buffer is emptied in the same way.
Common errors
Transferring is stricter than copying, and these mistakes throw a DataCloneError:
| Mistake | What happens |
|---|---|
| Transferring a buffer that is already detached | `DataCloneError` |
| Cloning a detached buffer, even without `transfer` | `DataCloneError` |
| Listing the same buffer twice in `transfer` | `DataCloneError` |
| Listing a `SharedArrayBuffer` in `transfer` | `DataCloneError`, because shared memory cannot be owned by one side |
| Reading the old typed array after transfer | No error, but `length` is `0` and reads return `undefined` |
The last row causes the most trouble because nothing throws. Code that keeps using the old view sees empty data without any warning.
const buf = new ArrayBuffer(4);
structuredClone(buf, { transfer: [buf] });
try {
structuredClone(buf, { transfer: [buf] });
} catch (err) {
console.log(err.name); // 'DataCloneError'
}When to use transfer
Use transfer when all three of these hold:
- The buffer is large enough that copying it costs noticeable time or memory.
- You do not need the original data after the call.
- No other code still holds views over the same buffer.
Within a single thread, structuredClone with transfer is mostly useful for taking clear ownership of data. The option matters most when data crosses into a worker. A later chapter covers how the same transfer mechanism works with postMessage. Browsers also accept other transferable types there, such as MessagePort and ImageBitmap.
Exercise
You run const a = new Uint8Array(1024); const b = new Uint16Array(a.buffer); const c = structuredClone({ a }, { transfer: [a.buffer] });. What are c.a.length, a.length and b.length afterwards, and why?
Show answer
c.a.length is 1024 because the result owns the moved memory. a.length is 0 because its buffer is detached. b.length is also 0 because b is a view over the same buffer, and transferring the buffer detaches it for every view that uses it.
Exercise
A function calls structuredClone(frame, { transfer: [frame.buffer] }) each time it is invoked, and the same frame typed array is passed in twice. What happens on the second call, and how would you fix it?
Show answer
The second call throws a DataCloneError because frame.buffer was detached by the first call. Fix it by passing fresh data each time, by copying without transfer when the caller still needs the data, or by checking frame.buffer.byteLength === 0 before transferring.