Benchmarks

suggest change

Benchmarking in Node.js measures the execution time, throughput, latency, and memory footprint of your code. Because Node.js runs on the V8 engine with Just-In-Time (JIT) compilation and an asynchronous event loop, accurate benchmarking requires controlling for JIT warmup, garbage collection (GC) cycles, and event loop delays.


1. Built-In Timing APIs

Node.js provides several native timing APIs ranging from simple console timers to nanosecond-precision performance hooks.

High-Resolution Monotonic Clock: process.hrtime.bigint()

process.hrtime.bigint() returns the current high-resolution real time in nanoseconds as a BigInt. Unlike Date.now(), it is strictly monotonic and unaffected by system clock drift.

import { setTimeout as sleep } from 'node:timers/promises';

async function measureDuration() {
  const start = process.hrtime.bigint();

  // Code under test
  await sleep(100);

  const end = process.hrtime.bigint();
  const elapsedNanoseconds = end - start;
  const elapsedMilliseconds = Number(elapsedNanoseconds) / 1_000_000;

  console.log(`Execution took ${elapsedMilliseconds.toFixed(3)} ms`);
}

measureDuration();

Modern Performance Hooks: node:perf_hooks

The node:perf_hooks module implements the W3C High Resolution Time and User Timing specifications:

import { performance, PerformanceObserver } from 'node:perf_hooks';

// Setup observer to listen for measure notifications
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(`[PERF] ${entry.name}: ${entry.duration.toFixed(3)} ms`);
  }
});
observer.observe({ entryTypes: ['measure'], buffered: true });

function processData() {
  performance.mark('json-parse-start');

  // Workload
  const items = Array.from({ length: 100_000 }, (_, i) => ({ id: i, value: Math.random() }));
  const serialized = JSON.stringify(items);
  JSON.parse(serialized);

  performance.mark('json-parse-end');
  performance.measure('JSON Serialize & Parse', 'json-parse-start', 'json-parse-end');
}

processData();

2. Micro-Benchmarking with tinybench

For statistically robust micro-benchmarks (including warmups, standard deviation, and operations-per-second calculations), modern projects use tinybench.

Installation

npm install tinybench

Comparing Array Iteration Methods

import { Bench } from 'tinybench';

const bench = new Bench({ time: 100, warmupIterations: 10 });
const data = Array.from({ length: 10_000 }, (_, i) => i);

bench
  .add('Classic for-loop', () => {
    let sum = 0;
    for (let i = 0; i < data.length; i++) {
      sum += data[i];
    }
    return sum;
  })
  .add('for...of loop', () => {
    let sum = 0;
    for (const val of data) {
      sum += val;
    }
    return sum;
  })
  .add('Array.prototype.forEach', () => {
    let sum = 0;
    data.forEach((val) => { sum += val; });
    return sum;
  })
  .add('Array.prototype.reduce', () => {
    return data.reduce((acc, val) => acc + val, 0);
  });

await bench.run();

console.table(bench.table());

Sample output (tinybench 6; numbers vary by machine):

┌─────────┬───────────────────────────┬──────────────────┬───────────────────┬────────────────────────┬────────────────────────┬─────────┐
│ (index) │ Task name                 │ Latency avg (ns) │ Latency med (ns)  │ Throughput avg (ops/s) │ Throughput med (ops/s) │ Samples │
├─────────┼───────────────────────────┼──────────────────┼───────────────────┼────────────────────────┼────────────────────────┼─────────┤
│ 0       │ 'Classic for-loop'        │ '8745.5 ± 6.21%' │ '6100.0 ± 400.00' │ '148493 ± 0.37%'       │ '163934 ± 11504'       │ 11435   │
│ 1       │ 'for...of loop'           │ '8199.0 ± 0.36%' │ '7900.0 ± 200.00' │ '124139 ± 0.18%'       │ '126582 ± 3288'        │ 12197   │
│ 2       │ 'Array.prototype.forEach' │ '20732 ± 0.79%'  │ '21100 ± 400.00'  │ '50347 ± 0.52%'        │ '47393 ± 916'          │ 4824    │
│ 3       │ 'Array.prototype.reduce'  │ '67479 ± 6.74%'  │ '56300 ± 3200.0'  │ '16335 ± 1.03%'        │ '17762 ± 1070'         │ 1482    │
└─────────┴───────────────────────────┴──────────────────┴───────────────────┴────────────────────────┴────────────────────────┴─────────┘

3. HTTP Server and Load Benchmarking with autocannon

For server applications (such as Express, Fastify, or raw node:http), micro-benchmarks do not capture network buffering or event loop saturation. Use autocannon to measure throughput and latency under load.

CLI Usage

npm install -g autocannon
autocannon -c 100 -d 10 http://localhost:3000/

Programmatic Load Test in Code

import autocannon from 'autocannon';

async function runLoadTest() {
  console.log('Initiating benchmark against http://localhost:3000/api/items...');

  const result = await autocannon({
    url: 'http://localhost:3000/api/items',
    connections: 50,
    duration: 10,
    pipelining: 1
  });

  console.log('--- Benchmark Results ---');
  console.log(`Requests/sec (avg): ${result.requests.average}`);
  console.log(`Throughput: ${(result.throughput.average / 1024 / 1024).toFixed(2)} MB/s`);
  console.log(`Latency p50: ${result.latency.p50} ms`);
  console.log(`Latency p99: ${result.latency.p99} ms`);
  console.log(`2xx Responses: ${result['2xx']}`);
  console.log(`Non-2xx Responses: ${result.non2xx}`);
}

runLoadTest();

4. Tracking Memory Footprint During Benchmarks

V8 allocates memory in heap spaces. Use process.memoryUsage() to record allocations:

function getHeapUsedMB() {
  const mem = process.memoryUsage();
  return (mem.heapUsed / 1024 / 1024).toFixed(2);
}

console.log(`Initial Heap: ${getHeapUsedMB()} MB`);

const cache = [];
for (let i = 0; i < 500_000; i++) {
  cache.push({ id: i, buffer: Buffer.alloc(128) });
}

console.log(`Heap after allocations: ${getHeapUsedMB()} MB`);

To run benchmarks with forced garbage collection between runs, start Node.js with --expose-gc:

node --expose-gc benchmark.js
if (global.gc) {
  global.gc(); // Force full garbage collection before taking measurements
}

5. Avoiding Common V8 Benchmarking Pitfalls

  1. Dead Code Elimination: The V8 JIT compiler can optimize away computations whose results are never read or returned. Always consume or return benchmark outputs.
  2. Missing JIT Warmup: V8 initially runs code via an interpreter (Ignition) and only compiles hot paths to native machine code (TurboFan) after hundreds or thousands of iterations. Always execute warmup loops before starting timer measurements.
  3. Monomorphic vs. Polymorphic Calls: Passing differently shaped objects into the same function triggers de-optimizations in V8 inline caches (ICs), artificially skewing results.
  4. Isolated Environments: Run benchmarks in a quiet, dedicated environment without competing CPU, disk, or network activity.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents