Sub topic 16
When to Use Shared Memory Instead of Message Passing
This chapter assumes you have read the earlier chapters on SharedArrayBuffer, cross-origin isolation, Atomics, and the mutex and ring buffer patterns. Here you will weigh the cost of those tools against plain postMessage.
The Default Is Message Passing
postMessage copies data with the structured clone algorithm. The receiving thread gets its own copy, so the two threads cannot race on it. This model is simple and safe, and it works in any browser context without special headers. Start with message passing and switch only when you have measured a problem it cannot solve.
Transferable objects remove the copy cost in many cases. When you transfer an ArrayBuffer, ownership moves to the receiving thread without copying, and the sender's buffer is detached:
// main.js
const worker = new Worker('worker.js');
const buf = new ArrayBuffer(8 * 1024 * 1024);
worker.postMessage(buf, [buf]);
console.log(buf.byteLength); // 0: the buffer now belongs to the worker
// worker.js
self.onmessage = (event) => {
console.log(event.data.byteLength); // 8388608
};If one thread works on the data at a time, transferring gives you zero-copy speed without any of the risks of shared memory.
What Shared Memory Buys You
Shared memory is worth it when several threads need the same bytes at the same time, or when they must coordinate more often than the event loop can deliver messages. Typical cases:
- Audio or video pipelines where a worker feeds an
AudioWorkletthrough a ring buffer at a fixed rate. - WebAssembly threads compiled from C, C++, or Rust, which expect a shared linear memory.
- Parallel algorithms where workers read one large dataset and write to separate regions of the same output.
- Counters, flags, and progress indicators that many threads update thousands of times per second.
What It Costs
| Concern | Message passing | Shared memory |
|---|---|---|
| Data races | Impossible | You prevent them with `Atomics` |
| Data shapes | Any cloneable object | Raw bytes through typed arrays |
| Browser setup | None | COOP and COEP headers required |
| Latency per update | One event loop turn | One atomic operation |
| Debugging | Ordinary logs and breakpoints | Bugs that depend on timing and are hard to reproduce |
| Blocking | Never blocks | `Atomics.wait` can stall a worker |
Cross-origin isolation also restricts embedding. Third-party iframes, scripts, and images must send CORP or CORS headers, and that can break ads, analytics, or payment widgets you rely on.
A Decision Path
A hybrid often works best. Use postMessage for commands and setup, and a SharedArrayBuffer only for the hot data path, such as samples, pixels, or a progress counter.
Exercise
A worker parses a 50 MB file into a Float64Array once, and then the main thread renders it. Should you use SharedArrayBuffer?
Show answer
No. Only one thread uses the data at a time, so transferring the underlying ArrayBuffer gives zero-copy handoff without cross-origin isolation or race risks.
Exercise
Four workers update a shared progress value about 10,000 times per second while the main thread displays it. Which approach fits, and why?
Show answer
A SharedArrayBuffer with Atomics.add in the workers and Atomics.load on the main thread. Sending 40,000 messages per second would flood the event loop, while atomic updates cost almost nothing. The page must be cross-origin isolated.