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

Transferring ArrayBuffers Between Threads

Transfer ownership of ArrayBuffers to avoid cloning overhead and enable zero-copy message passing.

Transferring ArrayBuffers Between Threads

You'll learn how to transfer ownership of ArrayBuffers between threads for maximum performance without copying data.

The Problem with Cloning

By default, when you pass data between threads using postMessage, Node.js creates a structured clone of the data. This means copying every byte from one thread's memory to another. For large ArrayBuffer objects (binary data like image pixels, audio samples, or file contents), this cloning is expensive and doubles memory usage temporarily.

Transfer Ownership Instead

Rather than cloning, you can transfer an ArrayBuffer. This moves ownership from the sending thread to the receiving thread in a zero-copy operation. Think of it like handing someone your car keys instead of building them an identical car—much faster and no duplication.

After transfer, the original ArrayBuffer in the sending thread becomes detached (unusable), with its byteLength set to 0. The receiving thread gets full access to the same underlying memory.

The Syntax

When calling postMessage, pass an array of transferable objects as the second argument:

// In the parent thread
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');

const buffer = new ArrayBuffer(1024 * 1024); // 1MB
// Transfer ownership to worker
worker.postMessage({ data: buffer }, [buffer]);

console.log(buffer.byteLength); // 0 - detached!
// In worker.js
const { parentPort } = require('worker_threads');

parentPort.on('message', ({ data }) => {
  console.log(data.byteLength); // 1048576 - full access!
});

The second argument [buffer] is the transfer list—an array of objects whose ownership should transfer rather than clone.

Key Takeaway: Transferring ArrayBuffer ownership between threads avoids cloning overhead, enables zero-copy messaging, and dramatically improves performance for large binary data at the cost of losing access in the sender.