Performance tips
Keeping the event loop free and reusing work makes Node apps fast.
In this page:
Performance tips
Avoid blocking the event loop with sync calls or heavy computation; use worker threads for CPU work. Cache repeated results, use streams for big data, enable compression, reuse connections and profile with node --prof or the inspector before optimizing.
Note:
Measure first: guessing bottlenecks wastes time.
Example: Performance tips
const { performance } = require("perf_hooks");
const cache = new Map();
function slowSquare(n) { let x = 0; for (let i = 0; i < 1e6; i++) x = n * n; return x; }
function cached(n) { if (!cache.has(n)) cache.set(n, slowSquare(n)); return cache.get(n); }
cached(9);
const t0 = performance.now(); cached(9); const hit = performance.now() - t0;
const t1 = performance.now(); slowSquare(9); const miss = performance.now() - t1;
console.log("cache hit faster than recompute:", hit < miss);
// Output:
// cache hit faster than recompute: true
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Blocking the loop with sync code
- Loading large files fully into memory
- Optimizing without profiling
Chapter Summary
- Keep the event loop free
- Use worker threads for CPU work
- Cache and stream
- Profile before optimizing
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: