The Cost of Worker Communication
What you'll learn: You'll understand how serialization overhead and message-passing latency can sometimes make workers slower than just running code on the main thread.
The Hidden Tax of Workers
Workers let you offload heavy computation, but they don't give you direct memory access to the main thread. Every piece of data you send via postMessage must be serialized (converted to a transferable format), sent across the worker boundary, then deserialized on the other side. This process takes time and CPU cycles.
Serialization Overhead
When you pass large objects or deeply nested structures, the structured clone algorithm must traverse every property, copy it, and reconstruct it in the worker's context. For small computations, this overhead can exceed the time saved by parallel execution.
Analogy: Imagine hiring a specialist consultant (worker) who works in another building. Even if they're brilliant, if you spend 10 minutes walking there, 15 minutes explaining the problem, and 10 minutes walking back—only for them to solve it in 2 minutes—you've wasted time compared to solving it yourself in 5 minutes.
Message-Passing Latency
Even with transferable objects (which avoid copies), there's still latency: queuing the message, context switching, and event loop scheduling on both sides. For tasks that complete in microseconds, this latency can dominate total execution time.
The Break-Even Point
Use performance APIs to measure if workers help. If a task takes <10ms and requires sending megabytes of data back and forth, you're likely slower with workers. Workers shine when computation time greatly exceeds communication cost.
Key Takeaway: Workers aren't free—serialization and message-passing add overhead. Profile your actual workload to ensure the computational savings outweigh the communication costs.