Performance: Why timing matters in Node.js
This concept affects how fast Node.js can respond to requests and handle tasks without blocking the event loop.
Jump into concepts and practice - no test required
import { readFile } from 'fs/promises'; async function readFiles() { const data1 = await readFile('file1.txt', 'utf8'); const data2 = await readFile('file2.txt', 'utf8'); console.log(data1, data2); } readFiles();
const fs = require('fs'); function readFiles() { const data1 = fs.readFileSync('file1.txt', 'utf8'); const data2 = fs.readFileSync('file2.txt', 'utf8'); console.log(data1, data2); } readFiles();
| Pattern | Event Loop Blocking | Task Delay | Responsiveness | Verdict |
|---|---|---|---|---|
| Synchronous blocking calls | Blocks event loop fully | Delays all queued tasks | High input latency | [X] Bad |
| Asynchronous non-blocking calls | Does not block event loop | Tasks run as soon as ready | Low input latency | [OK] Good |
process.nextTick run before setTimeout and setImmediate?process.nextTick runsprocess.nextTick callbacks run immediately after the current operation, before the event loop continues to the next phase.process.nextTick callbacks run immediately after the current operation completes, before the event loop continues. -> Option Bprocess.nextTick runs before timers and I/O [OK]setTimeout(fn, 0) runs after timers phase, process.nextTick runs before event loop phases, setImmediate runs after I/O events.setImmediate is designed to run callbacks after I/O events in the check phase.console.log('start');
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
process.nextTick(() => console.log('nextTick'));
console.log('end');console.log('start') and console.log('end') run immediately. process.nextTick runs after current operation but before event loop phases.process.nextTick runs first, then setImmediate callbacks, then setTimeout with 0 delay.setTimeout(() => console.log('timeout'));
setImmediate(() => console.log('immediate'));
process.nextTick(() => console.log('nextTick'));
process.nextTick(() => console.log('another nextTick'));process.nextTick callbacks always run before setImmediate and setTimeout, regardless of order in code.process.nextTick is used.setImmediate runs after I/O events, so use it for I/O callbacks to maintain order.process.nextTick for immediate callbacks and setImmediate for I/O callbacks. -> Option C