0 day streak
javascript / expert
Snippet

Zero-Copy Data Transfer with Transferable Objects

Transferable objects like ArrayBuffer or MessagePort can be moved between execution contexts (e.g., Main Thread to Web Worker) without cloning. This is a zero-copy operation that eliminates the overhead of serialization, though the object becomes 'detached' and unusable in the original context.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
const worker = new Worker('worker.js');
const largeBuffer = new Uint8Array(1024 * 1024 * 100).buffer; // 100MB
// Transfer ownership instead of cloning
worker.postMessage({ buffer: largeBuffer }, [largeBuffer]);
console.log(largeBuffer.byteLength); // 0 (detached)
// worker.js
self.onmessage = (e) => {
const buffer = e.data.buffer;
console.log('Received 100MB buffer instantly');
};
nextjs
Breakdown
1
[largeBuffer]
The second argument to postMessage defines the objects whose ownership is being transferred.
2
largeBuffer.byteLength // 0
After transfer, the buffer is detached from the main thread and has zero length.