Question presented to candidate: "You have a large ArrayBuffer, say a decoded audio buffer or a big binary payload, that a worker needs to process. If you just call postMessage with it, the browser has to structured-clone the whole thing, which means copying every byte. How would you hand it off without paying that copy cost, and what actually happens to your original buffer once you do?"
What a strong answer should cover:
- By default, an object passed to
postMessageis structured-cloned — for anArrayBuffer, that means a real, byte-for-byte copy, which gets expensive for a large buffer. - Passing a second argument to
postMessage— the transfer list, an array containing the specificArrayBuffer(s) to transfer — moves ownership instead of copying: the receiving side gets the real, same underlying memory, and the sending side's buffer is genuinely detached (itsbyteLengthbecomes0) immediately, synchronously, at thepostMessagecall itself. - A precise answer names the real trade-off this creates: the sender can no longer use that buffer at all after transferring it — this is a real, one-directional handoff, not a shared view.
- 📌 Interview term:
SharedArrayBufferis the deliberate alternative when BOTH sides genuinely need continued access — it cannot be placed in a transfer list at all, since it was never single-owner to begin with. - A strong answer names what belongs in a transfer list beyond
ArrayBuffer:MessagePortis the other classic example, and the list of transferable types has grown over time in both browsers and Node'sworker_threads. - A strong answer can quantify the real cost difference rather than just asserting "it's faster" — a genuine, measured before/after number for a specific buffer size makes the case concrete.
Clarifying questions expected:
- "Does the main thread still need this data for anything after handing it to the worker, or is the worker now the sole, permanent owner?" — if the main thread needs it again afterward, a transfer is the wrong tool and a copy (or SharedArrayBuffer) is genuinely required instead.
- "Is this a one-off large payload, or an ongoing stream of many smaller buffers?" — affects whether the per-call overhead of setting up the transfer list is worth it versus a different pattern.
Code / implementation expected: Yes — real, measured proof that the transfer is near-instant and genuinely detaches the sender's buffer, contrasted with a real measured copy cost for the identical data, is the concrete way to demonstrate the mechanism.