Transferable objects
Learn to transfer large data to a worker without copying memory.
Transferable objects
Copying large data to a worker is expensive. Transferable objects move memory from one side to the other without copying; this is called zero-copy transfer.
The main transferable types are ArrayBuffer, MessagePort and ImageBitmap. After the transfer, the data is no longer usable on the sender side; ownership moves to the receiver. You cannot send the same buffer twice.
Transfer list detail
The second parameter of postMessage is a transfer list: an array of objects to move. Each item in this list is handed to the receiver without being copied.
worker.postMessage(buffer, [buffer]);After the transfer, the buffer's byteLength becomes zero; the old reference is now an empty shell. Sending the same ArrayBuffer again throws a TypeError. Plan the transfer in one shot.
Exercise Transfer an ArrayBuffer
Create an ArrayBuffer named buffer (16 bytes). Then transfer ownership with worker.postMessage(buffer, [buffer]).
Show example solution
const buffer = new ArrayBuffer(16);
worker.postMessage(buffer, [buffer]);
Test yourself
-
What do transferable objects provide?
- Copy-free data transfer
- DOM access from a worker
- Variable sharing between two workers
- Automatic worker shutdown
Show answer
Copy-free data transfer — Correct! Transferable objects transfer ownership without copying memory.
-
Transfer the buffer
worker.postMessage(buffer, [____]);Show answer
worker.postMessage(buffer, [buffer]); -
Transferable matches
- ArrayBuffer
- transferable type
- [buffer]
- transfer list
- zero-copy
- copy-free transfer
- byteLength = 0
- after transfer