Lab 08: Performance Profiling

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm node:20-alpine sh

You can't optimize what you can't measure. This lab covers V8's built-in profiler, perf_hooks PerformanceObserver, trace events, heap profiling, and load testing with autocannon.


Step 1: perf_hooks — PerformanceObserver

The most important profiling tool in your daily Node.js work:

// file: perf-observer.js
const { performance, PerformanceObserver } = require('perf_hooks');

// Set up observer BEFORE creating marks
const obs = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(`${entry.name}: ${entry.duration.toFixed(3)}ms`);
  }
  obs.disconnect();
});
obs.observe({ entryTypes: ['measure'] });

// Benchmark: sort 100k elements
performance.mark('sort-start');
const arr = Array.from({ length: 100_000 }, () => Math.random());
arr.sort((a, b) => a - b);
performance.mark('sort-end');
performance.measure('array-sort-100k', 'sort-start', 'sort-end');

console.log('Sorted', arr.length, 'elements');

📸 Verified Output:

💡 PerformanceObserver is non-blocking and collects entries asynchronously. For synchronous measurements, use performance.now().


Step 2: Detailed Timing with performance.now()


Step 3: V8 Profiler with --prof

A minimal app to profile:

Run:

Expected output includes:

💡 Functions with high ticks percentage are your optimization targets. Focus on the top 3-5 functions.


Step 4: node:trace_events — Event Loop Tracing

Run with:


Step 5: Heap Profiling with --heap-prof


Step 6: autocannon Load Testing

Sample autocannon output:


Step 7: clinic.js — Production Profiling Suite

💡 Clinic Doctor gives a traffic-light analysis: red for blocking event loop, yellow for GC pressure, green for healthy. Use it before every major release.


Step 8: Capstone — Complete Performance Analysis Tool


Summary

Tool
Command
Use Case

perf_hooks

PerformanceObserver

Code-level timing, marks, measures

performance.now()

Inline

High-res timestamps

V8 profiler

--prof + --prof-process

CPU hotspots, flamegraph

Heap profiler

--heap-prof

Memory allocation hotspots

Trace events

--trace-events-enabled

Deep V8/libuv trace

autocannon

CLI

HTTP load testing

clinic doctor

clinic doctor --

Automatic bottleneck detection

clinic flame

clinic flame --

Interactive flamegraph

Last updated