Course contentsShow
← JavaScript
Lesson 2179 of 2,72345. Workers and ConcurrencyFree lesson

PostMessage vs Shared Memory: When to Use Each

Compare postMessage with SharedArrayBuffer and decide which concurrency primitive fits your use case.

PostMessage vs Shared Memory: When to Use Each

You'll learn: When to choose message-passing with postMessage versus direct shared memory access with SharedArrayBuffer.

Two Concurrency Models

JavaScript offers two fundamentally different approaches for multi-threaded communication:

  • PostMessage: Copies data between contexts (structured cloning or transferring)
  • SharedArrayBuffer: Multiple threads access the same memory directly

Think of postMessage like sending letters—each side gets its own copy, changes don't affect the original. SharedArrayBuffer is like a shared whiteboard—everyone sees the same surface, and changes are immediately visible to all.

When to Use PostMessage

Choose postMessage when:

  • Safety matters most: No risk of race conditions since data is copied
  • Complex data structures: Objects, nested arrays, and most JavaScript types work seamlessly
  • Infrequent communication: Occasional messages between main thread and workers
  • Simpler mental model: No synchronization primitives needed

The structured clone algorithm handles serialization automatically. It's the default choice for most worker communication.

When to Use SharedArrayBuffer

Choose shared memory when:

  • High-frequency updates: Continuous data streaming (audio buffers, game state, sensor data)
  • Performance critical: Avoiding copy overhead is essential
  • Numeric data: Working primarily with typed arrays (Int32Array, Float64Array, etc.)
  • Real-time coordination: Threads need instant visibility of changes

Trade-off: You must manually handle synchronization with Atomics, and only numeric arrays are directly shareable.

Decision Framework

Start with postMessage—it's safer and easier. Upgrade to SharedArrayBuffer only when profiling shows message-passing overhead is a genuine bottleneck. Most applications never need shared memory's complexity.

Key Takeaway: Use postMessage for simplicity and safety; reserve SharedArrayBuffer for high-performance scenarios with frequent numeric data updates where copy overhead becomes measurable.