Sharing Data with SharedArrayBuffer
You'll learn how to use SharedArrayBuffer for ultra-fast, shared memory communication between threads without copying data.
The Core Idea
Normally, when you send data between the main thread and a worker using postMessage, JavaScript copies the data. For large datasets or frequent updates, this copying creates overhead. SharedArrayBuffer creates a chunk of memory that both threads can access directly—no copying needed.
Think of it like a whiteboard in a shared room: instead of passing notes back and forth (copying), both people can read and write on the same board simultaneously.
How It Works
Create a SharedArrayBuffer, then access it via typed arrays in both threads:
// Main thread
const shared = new SharedArrayBuffer(16); // 16 bytes of shared memory
const view = new Int32Array(shared);
view[0] = 42;
const worker = new Worker('worker.js');
worker.postMessage({ shared });
// worker.js
self.addEventListener('message', (e) => {
const view = new Int32Array(e.data.shared);
console.log(view[0]); // 42 — reading shared memory
view[0] = 100; // Both threads see this change
});
Notice the SharedArrayBuffer itself is transferred, but the memory is shared—changes in one thread are immediately visible in the other.
When to Use It
Use SharedArrayBuffer when you need low-latency, high-frequency communication: game physics engines, audio processing, or real-time data analysis. Avoid it for simple tasks where message-passing suffices—shared memory introduces race conditions you'll need to manage carefully (typically with Atomics).
Key Takeaway:
SharedArrayBuffer enables zero-copy memory sharing between threads, delivering the lowest-latency communication for performance-critical concurrent tasks.