Performance: Creating worker threads
HIGH IMPACT
This concept affects how CPU-intensive tasks impact the main thread and overall responsiveness of a Node.js application.
import { Worker } from 'node:worker_threads'; const worker = new Worker(` const { parentPort } = require('worker_threads'); for (let i = 0; i < 1e9; i++) {} parentPort.postMessage('done'); `, { eval: true }); worker.on('message', msg => console.log(msg));
const heavyTask = () => {
// CPU-intensive loop
for (let i = 0; i < 1e9; i++) {}
};
heavyTask();| Pattern | CPU Usage | Main Thread Blocking | Responsiveness | Verdict |
|---|---|---|---|---|
| Synchronous heavy task on main thread | High CPU on main thread | Blocks main thread fully | Poor input responsiveness | [X] Bad |
| Heavy task in worker thread | High CPU but off main thread | Main thread free | Good input responsiveness | [OK] Good |