Lab 04: Node.js Performance

Time: 30 minutes | Level: Advanced | Docker: docker run -it --rm node:20-alpine sh

Overview

Profile and optimize Node.js applications: V8 --prof flag, flame graphs, deoptimization tracing, heap snapshots, perf_hooks PerformanceObserver, and memory leak detection.


Step 1: Performance Measurement with perf_hooks

const { performance, PerformanceObserver } = require('node:perf_hooks');
const v8 = require('node:v8');

// Mark and measure
performance.mark('algo:start');

let sum = 0;
for (let i = 0; i < 1e7; i++) sum += i;

performance.mark('algo:end');
performance.measure('loop', 'algo:start', 'algo:end');

const [entry] = performance.getEntriesByName('loop');
console.log(`Loop duration: ${entry.duration.toFixed(2)}ms`);
console.log(`Sum: ${sum}`);

// PerformanceObserver — async notifications
const obs = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(`[PERF] ${entry.name}: ${entry.duration.toFixed(2)}ms`);
  }
});
obs.observe({ entryTypes: ['measure', 'function'] });

// Wrap functions for automatic measurement
function timedFunction(name, fn) {
  return function(...args) {
    performance.mark(`${name}:start`);
    const result = fn.apply(this, args);
    performance.mark(`${name}:end`);
    performance.measure(name, `${name}:start`, `${name}:end`);
    return result;
  };
}

const timedSort = timedFunction('quicksort', (arr) => arr.sort());
timedSort(Array.from({length: 100000}, () => Math.random()));

Step 2: V8 Heap Statistics


Step 3: Memory Leak Detection


Step 4: V8 Profiling with --prof


Step 5: Deoptimization Tracing


Step 6: Heap Snapshot


Step 7: Benchmarking Patterns


Step 8: Capstone — perf_hooks Measurement

Run verification:

📸 Verified Output:


Summary

Tool
Command/API
Purpose

perf_hooks

performance.mark/measure

High-precision timing

PerformanceObserver

new PerformanceObserver()

Async perf notifications

V8 stats

v8.getHeapStatistics()

Memory usage

Heap snapshot

v8.writeHeapSnapshot()

Memory leak analysis

CPU profiler

node --prof

Function-level CPU time

Deopt tracing

node --trace-deopt

V8 optimization issues

Flame graph

clinic flame or 0x

Visual CPU profiling

Last updated