Performance: Worker thread vs child process
This concept affects how Node.js handles CPU-intensive tasks and parallelism, impacting responsiveness and throughput.
Jump into concepts and practice - no test required
const { Worker } = require('worker_threads');
const worker = new Worker('./heavyTask.js');
worker.on('message', (result) => {
console.log(result);
});const { fork } = require('child_process');
const child = fork('heavyTask.js');
child.on('message', (result) => {
console.log(result);
});| Pattern | Memory Usage | Startup Time | Communication Overhead | Verdict |
|---|---|---|---|---|
| Child Process | High (~5-10MB per process) | Slow (~10-50ms) | High (IPC via serialization) | [!] OK |
| Worker Thread | Lower (~1-5MB per thread) | Fast (~1-5ms) | Lower (Shared memory possible) | [OK] Good |
worker threads and child processes in Node.js?Worker class from the worker_threads module.new Worker('filename'). The fork and spawn methods are for child processes.new Worker() [OK]const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', msg => console.log('Parent got:', msg));
child.send('Hello');child.js sends back { reply: 'Hi' } on receiving a message?{ reply: 'Hi' } via process.send().child.on('message') receives the object and logs it as Parent got: { reply: 'Hi' }.const { Worker } = require('worker_threads');
const worker = Worker('worker.js');Worker class must be instantiated with the new keyword.Worker('worker.js') without new, causing a TypeError.new Worker() to create threads [OK]