Transferable Objects
Transferable Objects
Section titled “Transferable Objects”Introduction
Section titled “Introduction”Transferable objects allow data to be moved between threads with zero copying — ownership is transferred instead of cloning the data.
The Problem
Section titled “The Problem”// Without transferable objects, large data is CLONED (slow)const largeData = new ArrayBuffer(1024 * 1024 * 100); // 100MBworker.postMessage(largeData); // CLONING — 100MB copy!The Solution
Section titled “The Solution”// With transferable objects, ownership is TRANSFERRED (fast)const buffer = new ArrayBuffer(1024 * 1024 * 100); // 100MB
worker.postMessage(buffer, [buffer]);// buffer is now EMPTY in the main thread — ownership transferred// Much faster than cloning for large dataWhat Can Be Transferred
Section titled “What Can Be Transferred”// Transferable types:// - ArrayBuffer// - MessagePort// - ImageBitmap// - OffscreenCanvas// - ReadableStream, WritableStream, TransformStream
// After transfer, the original is detachedconst buf = new ArrayBuffer(1024);worker.postMessage(buf, [buf]);console.log(buf.byteLength); // 0 — detached!Summary
Section titled “Summary”- Transferable objects avoid cloning large data
- Ownership is transferred, not copied
- Original reference becomes empty after transfer
- Ideal for large ArrayBuffers, canvases, streams