Performance: Passing data to workers
This affects how quickly data is transferred between the main thread and worker threads, impacting responsiveness and CPU utilization.
Jump into concepts and practice - no test required
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
const largeBuffer = new SharedArrayBuffer(4 * 1000000);
worker.postMessage({ buffer: largeBuffer });const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
const largeData = { array: new Array(1000000).fill(0) };
worker.postMessage(largeData);| Pattern | Main Thread Block Time | Memory Copy | Serialization Cost | Verdict |
|---|---|---|---|---|
| Passing large objects by value | High (10-100ms) | High (~4MB) | High | [X] Bad |
| Passing SharedArrayBuffer | ~0ms | None | Low | [OK] Good |
workerData option in the Worker constructor.workerData from 'worker_threads'.workerData option in the Worker constructor -> Option AworkerData.workerData correctly; others use invalid keys.const { parentPort, workerData } = require('worker_threads');
parentPort.postMessage(workerData.num * 2);const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js', { workerData: { num: 5 } });
worker.on('message', (result) => console.log(result));workerData with { num: 5 } and multiplies num by 2.5 * 2 = 10 back via parentPort.postMessage, which the main thread logs.const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js', { workerData: 123 });
worker.on('message', (msg) => console.log(msg));worker.js expects workerData to be an object with a value property.workerData as an object with a value property, but a number 123 is passed.workerData.value.workerData.numbers, doubles each number, and sends back the new array. Which main thread code correctly passes data and listens for the result?workerData.numbers, so only code passing { workerData: { numbers: [1,2,3] } } works correctly.worker.on('message', (result) => console.log(result)) to log the doubled array sent back by the worker.