Advertisement
Advanced JavaScript, ArrayBuffer, TypedArrays & Binary Data

How do you share an ArrayBuffer between a Web Worker and the main thread without copying it?

Short answer

Use a SharedArrayBuffer instead of a regular ArrayBuffer, or transfer ownership of a regular ArrayBuffer via postMessage's transfer list, which moves (not copies) the buffer and leaves it unusable on the sender's side.

Save JavaScript mock interview
Advertisement
AModel answer
Use a SharedArrayBuffer instead of a regular ArrayBuffer, or transfer ownership of a regular ArrayBuffer via postMessage's transfer list, which moves (not copies) the buffer and leaves it unusable on the sender's side.
worker.postMessage(buffer, [buffer]); // transfers, doesn't copy
console.log(buffer.byteLength); // 0 after transfer
Real-world example
Transferring large decoded video frames to a worker for processing without duplicating memory.
Likely follow-ups
  • What extra requirements does SharedArrayBuffer have (COOP/COEP headers)?
Related topics