← Back to JavaScript, page 5

javascript-0097 · Hard senior

How do you measure JavaScript performance correctly, and what mistakes make a microbenchmark misleading?

Measure with performance.now or performance.mark and measure, not Date.now, run each case many times after a warm-up, report the median and spread rather than one run, and keep results in use so the engine cannot remove the work. Use a profiler for real bottlenecks, measure in the target environment, and treat microbenchmark results as hints, not proof.

Full answer

Use the right clock. performance.now() gives high-resolution time that never goes backward and is not affected by system clock changes. Date.now() is coarse and can jump. performance.mark and performance.measure give names to spans, and they show up in browser dev tools and in PerformanceObserver.

Why one run is not a measurement: the engine compiles code in tiers. The first calls run in an interpreter, and a hot function is later optimized. So early runs are slow, later runs are fast, and the garbage collector adds random pauses. A good method is:

  1. Warm up: run the function several times first and discard those timings.
  2. Repeat: take many samples, in batches if each call is very short.
  3. Summarize with the median and a spread such as the minimum and the 90th percentile. A mean is easily pulled by one GC pause.
  4. Compare cases in the same process, alternating them, so machine noise hits both.

Common mistakes that mislead:

  • Dead code elimination: if the result is never used, the engine may skip the work. Keep a result and use it, for example by adding it to a sink value and printing it at the end.
  • Constant inputs: the engine may fold or cache them. Use realistic, varied data.
  • Measuring setup together with the work, such as array creation inside the timed loop.
  • Timing in a dev build or with the debugger open.
  • Trusting a microbenchmark when the real cost is elsewhere: network, layout, or rendering. Use the browser Performance panel or node --cpu-prof to find the real hot spots first.
  • Timer precision limits: browsers coarsen timers for security, so measure many iterations and divide.

For user-facing code, also measure what users feel with real-user metrics such as Largest Contentful Paint and Interaction to Next Paint, not only function time.

The snippet below builds a small benchmark helper, compares two ways to sum an array, and prints only the facts that are the same on every run. Actual timings vary by machine, so they are not printed.

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

function benchmark(fn, { warmup = 5, samples = 15, iterations = 20 } = {}) {
  let sink = 0;
  for (let i = 0; i < warmup; i++) sink += fn();
  const times = [];
  for (let s = 0; s < samples; s++) {
    const start = performance.now();
    for (let i = 0; i < iterations; i++) sink += fn();
    times.push((performance.now() - start) / iterations);
  }
  times.sort((a, b) => a - b);
  return {
    median: times[Math.floor(times.length / 2)],
    min: times[0],
    p90: times[Math.floor(times.length * 0.9)],
    sink,
  };
}

const numbers = Array.from({ length: 100000 }, (_, i) => i % 97);

function sumLoop() {
  let total = 0;
  for (let i = 0; i < numbers.length; i++) total += numbers[i];
  return total;
}
function sumReduce() {
  return numbers.reduce((total, value) => total + value, 0);
}

console.log('both give the same result:', sumLoop() === sumReduce());

const a = benchmark(sumLoop);
const b = benchmark(sumReduce);
console.log('loop median is a positive number:', a.median > 0);
console.log('stats are ordered (min <= median <= p90):', a.min <= a.median && a.median <= a.p90);
console.log('sink keeps the work alive:', a.sink > 0 && b.sink > 0);

// mark and measure with a name, collected by an observer
const seen = [];
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) seen.push(entry.name);
});
observer.observe({ entryTypes: ['measure'] });

performance.mark('sum-start');
sumLoop();
performance.mark('sum-end');
const measure = performance.measure('sum-loop', 'sum-start', 'sum-end');
console.log('measure entry:', measure.name, measure.entryType, measure.duration >= 0);

setTimeout(() => {
  console.log('observer saw:', seen);
  observer.disconnect();
}, 20);

Run with Node.js v24.22.1 as js-97.js; two runs gave identical output. Output: both give the same result: true loop median is a positive number: true stats are ordered (min <= median <= p90): true sink keeps the work alive: true measure entry: sum-loop measure true observer saw: [ 'sum-loop' ]

Key points

  • Use performance.now and mark/measure; Date.now is coarse and can jump.
  • Warm up, repeat many times, and report the median and spread.
  • Keep results in use so dead code elimination cannot remove the work.
  • Do not time setup, constant inputs, or debug builds.
  • Profile to find the real bottleneck first; microbenchmarks are hints only.

Common mistakes

  • Timing one call and drawing a conclusion.
  • Using Date.now for short intervals.
  • Letting the engine remove the work because the result is unused.
  • Optimizing a function that a profile does not show as a bottleneck.

Follow-ups

  • Why do JavaScript engines need a warm-up, and what is tiered compilation?
  • Which user-facing metrics would you track for a web page, and how do they differ from function timings?
  • How would you detect a performance regression automatically in continuous integration?

Tips

  • Describe the method: warm-up, many samples, median, same process, alternate cases.
  • Name dead code elimination as the main trap.
  • Say that profiling comes before micro-optimizing.