Performance: Why worker threads matter
HIGH IMPACT
This concept affects how Node.js handles CPU-intensive tasks without blocking the main event loop, improving responsiveness and throughput.
const http = require('http'); const { Worker } = require('worker_threads'); http.createServer((req, res) => { const worker = new Worker(` const { parentPort } = require('worker_threads'); let count = 0; for (let i = 0; i < 1e9; i++) count += i; parentPort.postMessage(count); `, { eval: true }); worker.on('message', (count) => res.end(`Count is ${count}`)); worker.on('error', (err) => { res.statusCode = 500; res.end('Worker error'); }); }).listen(3000);
const http = require('http'); http.createServer((req, res) => { // Heavy computation blocking main thread let count = 0; for (let i = 0; i < 1e9; i++) count += i; res.end(`Count is ${count}`); }).listen(3000);
| Pattern | Event Loop Blocking | CPU Utilization | Responsiveness | Verdict |
|---|---|---|---|---|
| Synchronous CPU task on main thread | Blocks event loop fully | Single core maxed | Poor, high input delay | [X] Bad |
| CPU task in worker thread | No blocking of main event loop | Multiple cores utilized | Good, low input delay | [OK] Good |