Sub topic 10
Moving Instead of Copying: The transfer Option
This chapter assumes you already know how structuredClone makes deep copies, that ArrayBuffer and typed arrays such as Uint8Array are on its list of supported types, and how a DataCloneError is thrown. You should also be able to run code in Node.js 17 or later, or in a modern browser console.
Up to now, every call to structuredClone has produced a full, independent copy. For most data that is what you want. Binary data is different. A 200 MB image, an audio recording, or a large mesh of vertex data is expensive to duplicate, and often you are done with the original as soon as the copy exists. The transfer option handles that case: instead of copying the bytes, structuredClone moves the underlying memory into the result and leaves the original object empty.
The Shape of the Call
structuredClone takes a second argument, an options object with one property, transfer. It holds an array of transferable objects. A transferable is an object whose underlying resource can be handed from one owner to another. On every runtime that has structuredClone, ArrayBuffer is transferable. Browsers add others, such as MessagePort, ImageBitmap, OffscreenCanvas and the stream classes.
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 result moved is a new ArrayBuffer object, but it holds the same block of memory the original used. No bytes were copied. The original buffer object still exists, because your variable still points to it. It just no longer owns any memory. That state is called detached.
What Detached Means
A detached ArrayBuffer is permanently empty. You cannot reattach it, resize it back, or read old data through it. Any views that were built on top of it, such as Uint8Array or DataView, are affected too, and they react in different ways.
const buffer = new ArrayBuffer(4);
const bytes = new Uint8Array(buffer);
const view = new DataView(buffer);
bytes.set([10, 20, 30, 40]);
const moved = structuredClone(buffer, { transfer: [buffer] });
console.log(new Uint8Array(moved)); // Uint8Array(4) [ 10, 20, 30, 40 ]
console.log(buffer.byteLength); // 0
console.log(bytes.length); // 0
console.log(bytes[0]); // undefined
bytes[0] = 99; // silently ignored
console.log(bytes[0]); // undefined
try {
bytes.fill(1);
} catch (err) {
console.log(err.name); // 'TypeError'
}
try {
view.getUint8(0);
} catch (err) {
console.log(err.name); // 'TypeError'
}
if ('detached' in ArrayBuffer.prototype) {
console.log(buffer.detached); // true
}The behaviour is uneven. Indexed reads on a detached typed array return undefined, and indexed writes do nothing, with no error. Most typed array methods (fill, map, slice, subarray and so on) throw a TypeError, and DataView getters and setters throw as well. The quiet failures cause the most trouble. A loop that reads bytes[i] against bytes.length simply runs zero times and produces an empty result, and nothing tells you why.
The ArrayBuffer.prototype.detached property is part of ES2024. Older runtimes do not have it, which is why the example checks for it first. On those runtimes, byteLength === 0 is the usual stand-in. It is not a perfect test, because a real zero-length buffer looks the same.
| Operation on a detached buffer or its views | Result |
|---|---|
| `buffer.byteLength` | `0` |
| `buffer.detached` (ES2024) | `true` |
| `typedArray.length`, `typedArray.byteLength` | `0` |
| `typedArray[i]` read | `undefined` |
| `typedArray[i] = x` write | Ignored, no error |
| `typedArray.fill()`, `.slice()`, `.map()` and other methods | `TypeError` |
| `dataView.getUint8()`, `dataView.byteLength` | `TypeError` |
| `new Uint8Array(buffer)` | `TypeError` |
| `structuredClone(buffer)` | `DataCloneError` |
Transferring Typed Arrays and Nested Buffers
You transfer buffers, not views. A Uint8Array is not transferable, so putting one in the transfer list throws a DataCloneError. Put its .buffer in the list instead, and pass the view (or any structure containing it) as the value:
const pixels = new Uint8Array([1, 2, 3, 4]);
try {
structuredClone(pixels, { transfer: [pixels] });
} catch (err) {
console.log(err.name); // 'DataCloneError'
}
const copy = structuredClone(pixels, { transfer: [pixels.buffer] });
console.log(copy); // Uint8Array(4) [ 1, 2, 3, 4 ]
console.log(pixels.length); // 0The value and the transfer list are separate. The value describes what the result looks like. The transfer list says which buffers inside it should move instead of being copied. Any buffer reachable from the value that is not in the list is copied as usual. That lets you mix the two in one call:
const frame = {
id: 7,
meta: { width: 2, height: 2 },
pixels: new Uint8Array([255, 0, 0, 255]),
thumbnail: new Uint8Array([9, 9])
};
const result = structuredClone(frame, { transfer: [frame.pixels.buffer] });
console.log(result.pixels); // Uint8Array(4) [ 255, 0, 0, 255 ]
console.log(frame.pixels.length); // 0 (moved)
console.log(frame.thumbnail.length); // 2 (copied, original untouched)
console.log(result.meta === frame.meta); // false (plain data is still deep-copied)The rest of the object graph is cloned exactly as in earlier chapters. Shared references stay shared too. If two typed arrays view the same buffer and you transfer that buffer, both views in the result point to the single transferred buffer, and both views in the original go empty.
Failure Modes
The transfer list is validated strictly. Each of these throws a DataCloneError:
- The list contains something that is not transferable, such as a typed array, a plain object, or a
Map. - The same buffer appears twice in the list.
- A buffer in the list is already detached.
- A buffer in the list cannot be detached. A
SharedArrayBufferis shared by design and cannot be transferred, and neither can the buffer behind aWebAssembly.Memory.
const buf = new ArrayBuffer(16);
function tryClone(label, value, transfer) {
try {
structuredClone(value, { transfer });
console.log(label, 'ok');
} catch (err) {
console.log(label, err.name);
}
}
tryClone('duplicate entry', buf, [buf, buf]); // duplicate entry DataCloneError
tryClone('first transfer', buf, [buf]); // first transfer ok
tryClone('already detached', buf, [buf]); // already detached DataCloneError
tryClone('shared memory', new Uint8Array(4), [new SharedArrayBuffer(4)]);
// shared memory DataCloneErrorOrder matters when the value itself is the problem. In the HTML specification, structuredClone serializes the whole value first and detaches the transfer list only after serialization succeeds. If the value contains a function, the call throws a DataCloneError and your buffers stay attached and intact. You can retry after removing the bad value without losing the data.
const data = new ArrayBuffer(8);
try {
structuredClone({ data, onDone: () => {} }, { transfer: [data] });
} catch (err) {
console.log(err.name); // 'DataCloneError'
}
console.log(data.byteLength); // 8 (not detached, because serialization failed first)Why Bother in a Single Thread?
Within one thread, the copy and the original live in the same memory space, so the speed gain is only about skipping the byte copy. For a few kilobytes that saving is tiny. It starts to matter when buffers are large or copied often:
| Approach | Byte copy | Original after the call | Peak memory |
|---|---|---|---|
| `structuredClone(buf)` | Yes, proportional to size | Intact, independent | About twice the buffer size |
| `structuredClone(buf, { transfer: [buf] })` | No | Detached | About one buffer |
| `buf.transfer()` (ES2024) | No | Detached | About one buffer |
| `buf.slice(0)` | Yes | Intact, independent | About twice the buffer size |
Peak memory is often a bigger concern than time. Copying a 500 MB buffer briefly needs 1 GB, which can crash a browser tab or a memory-limited container. A transfer does not have that spike.
If all you need is to move one standalone buffer, ArrayBuffer.prototype.transfer() from ES2024 is more direct. It returns a new buffer holding the old memory, detaches the original, and can also resize the buffer as it moves it, as in buf.transfer(newLength). structuredClone with transfer is the better choice when the buffer sits inside a larger structure you also want deep-copied, or when your runtime has structuredClone but not ArrayBuffer.prototype.transfer.
The main use of transfer lists is outside a single thread, when you send data to a worker or another window. There, the receiving side runs in a separate memory space, and transferring hands over memory that would otherwise be serialized and duplicated across the boundary. The same transfer list syntax appears in postMessage, which the next chapter covers.
A Practical Helper
Building transfer lists by hand gets error-prone once structures grow. This helper walks a value, collects every distinct, non-shared, non-detached ArrayBuffer it finds, and returns a list that is safe to pass:
function collectTransferables(value, seen = new Set(), out = new Set()) {
if (value === null || typeof value !== 'object' || seen.has(value)) return out;
seen.add(value);
if (value instanceof ArrayBuffer) {
if (value.byteLength > 0 || value.detached === false) out.add(value);
return out;
}
if (ArrayBuffer.isView(value)) {
if (value.buffer instanceof ArrayBuffer) collectTransferables(value.buffer, seen, out);
return out;
}
if (value instanceof Map) {
for (const [k, v] of value) {
collectTransferables(k, seen, out);
collectTransferables(v, seen, out);
}
return out;
}
if (value instanceof Set) {
for (const v of value) collectTransferables(v, seen, out);
return out;
}
for (const key of Object.keys(value)) collectTransferables(value[key], seen, out);
return out;
}
const scene = {
a: new Float32Array([1, 2, 3]),
b: new Uint8Array(8),
sameBufferAsA: null
};
scene.sameBufferAsA = new Uint8Array(scene.a.buffer);
const transfer = [...collectTransferables(scene)];
console.log(transfer.length); // 2 (a's buffer is listed once despite two views)
const moved = structuredClone(scene, { transfer });
console.log(moved.a); // Float32Array(3) [ 1, 2, 3 ]
console.log(scene.a.length); // 0The Set prevents the duplicate-entry error, and the instanceof ArrayBuffer check excludes SharedArrayBuffer, which is a different class. The detached check uses byteLength > 0 and falls back to detached === false, so it also works on runtimes without the ES2024 property. It skips zero-length buffers there, which is harmless because those are cheap to copy.
Exercise
You run const out = structuredClone({ img: view }, { transfer: [view.buffer] }), where view is a Uint8Array of length 1000. Afterwards, what do view.length, view[0] and view.slice(0, 1) produce, and what is out.img.length?
Show answer
view.length is 0 and view[0] is undefined, because the underlying buffer was detached. view.slice(0, 1) throws a TypeError, since typed array methods refuse to work on a detached buffer. out.img.length is 1000, because the result's Uint8Array views the transferred memory.
Exercise
A function calls structuredClone(payload, { transfer: [buf] }), where payload contains buf and also a callback function. Is buf detached after the call throws? Why?
Show answer
No. The call throws a DataCloneError while serializing the function. The specification serializes the whole value before detaching anything in the transfer list, so buf keeps its memory and its original byteLength.
Exercise
You need to move one 300 MB ArrayBuffer to a new variable in the same thread, and you will never use the old one again. Name two ways to avoid the byte copy, and say when you would prefer structuredClone over the other one.
Show answer
Use structuredClone(buf, { transfer: [buf] }) or buf.transfer(). Both move the memory and detach the original. Prefer structuredClone when the buffer is part of a larger structure that you also want deep-copied in the same call, or when the runtime lacks the ES2024 ArrayBuffer.prototype.transfer method.