← Back to Node.js Course | Chapter 10: Deployment & Best Practices | Lesson 7 of 7

Performance tips

Keeping the event loop free and reusing work makes Node apps fast.

In this page:

  1. Performance tips

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

javascript
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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Blocking the loop with sync code
  2. Loading large files fully into memory
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.