javascript / expert
Snippet
Zero-copy Data Transfer in Worker Threads
Transferable objects allow moving data between threads without cloning, which is critical for high-performance Node.js applications. By passing the ArrayBuffer in the second argument of postMessage, ownership is transferred, ensuring near-instant communication regardless of data size, at the cost of the original thread losing access to the memory.
snippet.js
1
2
3
4
5
6
7
8
const { Worker } = require('worker_threads');const buffer = new ArrayBuffer(1024 * 1024); // 1MBconst worker = new Worker('./worker.js');// Transfer ownership, making 'buffer' inaccessible in the main threadworker.postMessage({ data: buffer }, [buffer]);console.log(buffer.byteLength); // 0
nodejs
Breakdown
1
worker.postMessage({ data: buffer }, [buffer]);
The second argument lists objects to be transferred instead of cloned.
2
console.log(buffer.byteLength); // 0
After transfer, the original buffer is 'detached' and emptied.