Sub topic 15
Moving Buffers Between Workers with postMessage
This chapter assumes you know how to create an ArrayBuffer and wrap it in a typed array. It also assumes you have basic familiarity with Web Workers: new Worker(), postMessage, and onmessage. The previous chapter covered transfer() and detached buffers, which this chapter builds on.
Copying Versus Transferring
When you call postMessage(data), the browser serializes data with the structured clone algorithm. For an ArrayBuffer, that means copying every byte. A 100 MB buffer costs 100 MB of extra memory plus the time it takes to copy it.
The second argument to postMessage is a transfer list. Any buffer in that list moves to the receiver instead of being copied. The receiver gets the same memory, and the sender's buffer becomes detached: its byteLength drops to 0 and it can no longer be used.
A Round Trip
The main thread sends a buffer, the worker doubles each byte, and the worker sends the buffer back. No bytes are copied in either direction.
// main.js
const worker = new Worker('worker.js');
const bytes = new Uint8Array([1, 2, 3, 4]);
worker.postMessage(bytes.buffer, [bytes.buffer]);
console.log(bytes.length); // 0, the view's buffer is detached
worker.onmessage = (event) => {
const result = new Uint8Array(event.data);
console.log(result); // Uint8Array [2, 4, 6, 8]
};// worker.js
self.onmessage = (event) => {
const buffer = event.data;
const bytes = new Uint8Array(buffer);
for (let i = 0; i < bytes.length; i++) {
bytes[i] *= 2;
}
self.postMessage(buffer, [buffer]);
};The transfer list contains bytes.buffer and not bytes, because buffers are transferable and typed arrays are not. You can post the typed array itself as the message, as long as you list its buffer: postMessage(bytes, [bytes.buffer]). The receiver then gets a Uint8Array with the same byteOffset and length.
postMessage also accepts an options object: worker.postMessage(buf, { transfer: [buf] }).
Trying It Without a Worker
structuredClone uses the same algorithm and accepts the same transfer option, so you can test the behavior in one script:
const buf = new ArrayBuffer(8);
const view = new Uint8Array(buf);
const copy = structuredClone(buf);
console.log(buf.byteLength, copy.byteLength); // 8 8
const moved = structuredClone(buf, { transfer: [buf] });
console.log(buf.byteLength, moved.byteLength); // 0 8
console.log(buf.detached, view.length, view[0]); // true 0 undefinedCommon Errors
| Mistake | Result |
|---|---|
| Using the buffer after sending it | Views report length 0, reads return `undefined`, and many methods throw `TypeError` |
| Transferring a buffer that is already detached | `DataCloneError` |
| Listing the same buffer twice in the transfer list | `DataCloneError` |
| Forgetting the transfer list | No error, but the buffer is silently copied |
| Putting a `SharedArrayBuffer` in the transfer list | `DataCloneError`; shared buffers are posted without the list |
Exercise
After running const a = new Float32Array(4); worker.postMessage(a, [a.buffer]);, what do a.length and a.buffer.byteLength return in the main thread, and what does the worker receive?
Show answer
Both return 0, because the buffer is detached. The worker receives a Float32Array of length 4 over the same 16 bytes of memory, with no copy made.
Exercise
You need to send bytes 0–99 of a 10 MB Uint8Array named big to a worker and keep using big afterward. What should you post?
Show answer
Copy the range first with const part = big.slice(0, 100); and then call worker.postMessage(part, [part.buffer]);. Transferring big.subarray(0, 100).buffer would move all 10 MB and detach big.