Transferable Objects: Zero-Copy Data Transfer
What you'll learn: How to transfer ownership of certain objects between contexts (like workers) without copying their data, dramatically improving performance.
The Performance Problem with Copying
When you use postMessage to send data between a main thread and a worker, JavaScript normally creates a deep copy using the structured clone algorithm. For large datasets like ArrayBuffer instances containing millions of bytes, this copying takes time and doubles memory usage temporarily.
Zero-Copy Transfer with Transferables
Transferable objects solve this by transferring ownership rather than copying. When you transfer an ArrayBuffer, the original context loses access to it completely—the data moves to the receiving context without duplication.
Think of it like handing someone your car keys instead of building them an identical car. The original owner can no longer drive the car, but the transfer is instant and costs nothing.
How to Transfer Objects
Pass an array of transferable objects as the second argument to postMessage:
// Main thread
const buffer = new ArrayBuffer(1024 * 1024); // 1MB
const view = new Uint8Array(buffer);
view[0] = 42;
worker.postMessage({ data: buffer }, [buffer]);
// After this, 'buffer' is now detached in the main thread
console.log(buffer.byteLength); // 0 - can't use it anymore!
// Worker thread
self.addEventListener('message', (e) => {
const buffer = e.data.data;
console.log(buffer.byteLength); // 1048576 - ownership transferred!
});
What Can Be Transferred?
Only certain objects support transferring: ArrayBuffer, MessagePort, ImageBitmap, OffscreenCanvas, and a few others. Regular objects, arrays, and primitives are always cloned.
Key Takeaway: Use transferable objects like ArrayBuffer in the second argument of postMessage to move large binary data between contexts instantly without copying, though the sender permanently loses access to the transferred data.