AceDevHub
Advanced JavaScript Interview QuestionsAdvancedComparison

JavaScript · Question 93

What is the difference between cloning and transferring data when communicating with a Web Worker?

Direct answer

Structured cloning creates an independent serialized/deserialized value in the destination realm, while transferring moves ownership of transferable resources such as an ArrayBuffer’s backing data so the original sender can no longer use that transferred buffer.

Calling worker.postMessage(data) normally uses the platform’s structured serialization machinery for supported values. For large binary payloads this can imply copying or reconstruction work. With a transfer list, code can instead transfer certain resources.

For example, worker.postMessage({ buffer }, [buffer]) transfers the ArrayBuffer rather than keeping the same usable backing store on both sides. The sender’s transferred buffer becomes detached, while the receiving side gets ownership of the transferred data.

  • Transfer when ownership can safely move and avoiding a large copy matters.
  • Clone when both sides need independent usable values.
  • A transfer is not a magical shared-memory operation. If actual shared memory is needed, that is a different model involving SharedArrayBuffer and synchronization.