Skip to content

Performance Measurement

The Course
•
20 min study

Performance work starts with a workload and a question. Are repeated lookups dominating runtime? Is allocation growing with input size? A single elapsed number without input size, repetitions and environment tells little.

Use performance.now for a monotonic elapsed measurement. Warm up the code, repeat comparable work, keep a checksum so the work has an observed result, and compare distributions across runs. Do not claim a tiny timing difference proves one implementation is faster on every machine.

The playground is a worker with startup and shared runtime costs. It is good for learning measurement mechanics, not publishing authoritative benchmark results. Exact durations are deliberately not part of this lesson's predicted output. The boolean check below only establishes that a duration was recorded; the comparison further down shows how to get numbers worth reading.

For concurrency, increasing the limit can increase memory or remote load without improving throughput. Synchronous CPU-bound callbacks still block the worker. Measure the resource and outcome that matter to users.

Predict, run, and explain

Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.

Predict, then run JavaScript
const started = performance.now();
let checksum = 0;

for (let n = 0; n < 10000; n++) {
  checksum += n;
}

const elapsed = performance.now() - started;

console.log(checksum);
console.log(elapsed >= 0);
Check your prediction
Text
49995000
true

Validate the work before comparing durations

A fast wrong result is not a useful optimization. Check an output or checksum before interpreting measured time. Keep input preparation and result consumption deliberate so two variants are compared on the same workload.

Timing varies with warmup, scheduling and the environment. Report observations rather than asserting one fixed duration in a test. If a measurement is too small to distinguish from timer resolution, repeat meaningful work locally and keep correctness checks independent of timing.

Validate the work before comparing durations: trace JavaScript
const values = [1, 2, 3, 4];
const start = performance.now();
let total = 0;

for (const value of values) {
  total += value;
}

const elapsed = performance.now() - start;

console.log(total);
console.log(Number.isFinite(elapsed) && elapsed >= 0);
Check your prediction
Text
10
true

The prediction checks correctness and a valid measurement shape, not an exact speed. A single four-item run is a teaching example, not a reliable performance conclusion.

Validate the work before comparing durations: contrast JavaScript
const values = [1, 2, 3, 4];
let loop = 0;

for (const value of values) {
  loop += value;
}

const formula = (values.length * (values.length + 1)) / 2;

console.log(loop === formula);
console.log(loop);
Check your prediction
Text
true
10

The formula is valid for this special consecutive input, not arbitrary arrays. A faster special-case algorithm must state its preconditions instead of quietly changing the problem being measured.

Try the rule on new inputs

Compare several input sizes and verify results first. State the workload and environment with any timing claim. Do not make a fixed timing threshold part of the portable lesson test suite.

Compare two versions over many runs

One timing is a single sample from a noisy process. To compare two implementations, run each many times on the same input, skip the first few runs while the engine warms up, alternate the two so a slow moment hits both, and look at the median and the range rather than one number. Check that the results agree before reading any timing.

The program below compares counting even numbers with filter(...).length, which builds a whole new array, against a plain loop. Predict which is faster and by roughly how much, then run it two or three times.

Medians of 20 batched samples each JavaScript
const values = Array.from({ length: 20000 }, (_, i) => (i * 7919) % 1000);

function countEvenFilter(list) {
  return list.filter(n => n % 2 === 0).length; // builds a new array
}

function countEvenLoop(list) {
  let count = 0;
  for (const n of list) if (n % 2 === 0) count += 1;
  return count;
}

// One call takes about 0.1 ms, close to the browser's timer resolution,
// so each sample times a batch of calls and divides.
const BATCH = 200;

function timeBatch(fn) {
  let result;
  const started = performance.now();
  for (let i = 0; i < BATCH; i++) result = fn(values);
  const total = performance.now() - started;
  return { result, total, perCall: total / BATCH };
}

const samples = { filter: [], loop: [] };
const totals = [];
for (let run = 0; run < 30; run++) {
  // Alternate the two so a slow moment affects both equally.
  const a = timeBatch(countEvenFilter);
  const b = timeBatch(countEvenLoop);
  if (a.result !== b.result) throw new Error("implementations disagree");
  if (run >= 10) {
    // the first 10 samples are warm-up
    samples.filter.push(a.perCall);
    samples.loop.push(b.perCall);
    totals.push(a.total, b.total);
  }
}

const median = list => [...list].sort((x, y) => x - y)[Math.floor(list.length / 2)];
const fmt = ms => ms.toFixed(4);

console.log(`results agree; shortest timed batch ${Math.min(...totals).toFixed(1)} ms`);
for (const [name, list] of Object.entries(samples)) {
  const sorted = [...list].sort((x, y) => x - y);
  console.log(`${name.padEnd(6)} median ${fmt(median(list))} ms per call (range ${fmt(sorted[0])}-${fmt(sorted.at(-1))}, ${list.length} samples)`);
}

const f = median(samples.filter);
const l = median(samples.loop);
console.log(
  f > 0 && l > 0
    ? `filter / loop median ratio: ${(f / l).toFixed(2)}`
    : "a median is 0: the batches are still too short for this timer"
);

One call of either function takes about a tenth of a millisecond, which is too close to the timer to measure on its own. Browsers deliberately coarsen performance.now(), to about 0.1 ms or more in an ordinary page. A single call can therefore read as 0 or as one tick, and a median of 0 would make the ratio NaN or Infinity. So each sample times a batch of 200 calls and divides. The first line prints the shortest batch, so you can check that every sample is far above the timer's step, and the last line refuses to divide by a zero median.

Your numbers will differ from anyone else's, and between your own runs. In Node on the machine used to write this lesson, the loop's median was about 0.011 ms per call and filter's about 0.024 ms, a ratio between 2.1 and 2.6 over five runs. Look at the ranges too: filter's highest sample was often four times its median, from a slow moment or a garbage collection. One unlucky single timing could have suggested almost any ratio. Notice what the program asserts (that both versions agree) and what it only reports (times and ratio). A test that asserted "loop is twice as fast" would fail on some machines and pass on others.

Trace the contract before building

Choose a question before timing. Are you comparing total latency, responsiveness while work runs, throughput or retained memory? A faster total time can still make the interface less responsive, and a concurrency change may protect one resource while loading another.

Keep workloads, warm-up and environment assumptions visible. Repeat measurements and distinguish algorithmic growth from fixed overhead. Tests should establish correctness before comparing speed; otherwise an implementation that skips work can appear impressively fast. A browser demonstration provides evidence for that workload, not a universal ranking of every runtime or machine.

Your turn

Exercise

Report a median, assert only what is stable

Write timeRuns(fn, input, { warmup, runs, batch }). It calls fn(input) warmup times without timing. Then it takes runs samples: each sample calls fn(input) batch times between two performance.now() readings and records the time per call. It returns the last result, the sorted list of per-call times and the median. The code below uses it to compare building a string with += against join. It prints only the facts that do not depend on the machine, and sends the timings to console.error, which this editor shows like any other output. The checked output is:

Text
results agree: true
runs each: 21, 21
median inside range: true
Your workspace JavaScript
function timeRuns(fn, input, { warmup, runs, batch }) {
  // Call fn(input) `warmup` times without timing. Then take `runs`
  // samples: each one times `batch` calls and records ms per call.
  // Return { result, times (sorted), median }.
  return { result: fn(input), times: [], median: 0 };
}

const words = Array.from({ length: 5000 }, (_, i) => `w${i % 300}`);

function joinWithPlus(list) {
  let text = "";
  for (const word of list) text += word + " ";
  return text.trimEnd();
}

function joinWithJoin(list) {
  return list.join(" ");
}

// One call is far below a millisecond, so each sample times 300 calls.
const options = { warmup: 20, runs: 21, batch: 300 };
const plus = timeRuns(joinWithPlus, words, options);
const join = timeRuns(joinWithJoin, words, options);

console.log(`results agree: ${plus.result === join.result}`);
console.log(`runs each: ${plus.times.length}, ${join.times.length}`);
console.log(
  `median inside range: ${[plus, join].every(m => m.times[0] <= m.median && m.median <= m.times.at(-1))}`
);

// Timings vary from run to run, so they are reported, not asserted.
// console.error keeps them apart from the checked output above.
console.error(`+= median ${plus.median.toFixed(4)} ms, join median ${join.median.toFixed(4)} ms per call`);
console.error(
  plus.median > 0 && join.median > 0
    ? `ratio (+= / join): ${(plus.median / join.median).toFixed(2)}`
    : "a median is 0: raise batch until every sample is well above the timer's resolution"
);
Hint 1: the idea

A median needs many separate samples, and each sample must be long enough for the timer to see. One call here takes a few hundredths of a millisecond, below what a browser timer can resolve, so a sample times a batch of calls and divides by the batch size.

Hint 2: a first step

Write the warm-up loop, then an outer loop over runs that reads performance.now() once before and once after an inner loop of batch calls. Run it: runs each should show 21, 21 even before you compute the median. Then sort and pick the middle element.

Show one solution
JavaScript
function timeRuns(fn, input, { warmup, runs, batch }) {
  for (let i = 0; i < warmup; i++) fn(input);
  const times = [];
  let result;
  for (let i = 0; i < runs; i++) {
    const started = performance.now();
    for (let j = 0; j < batch; j++) result = fn(input);
    times.push((performance.now() - started) / batch); // ms per call
  }
  times.sort((a, b) => a - b);
  return { result, times, median: times[Math.floor(times.length / 2)] };
}

const words = Array.from({ length: 5000 }, (_, i) => `w${i % 300}`);

function joinWithPlus(list) {
  let text = "";
  for (const word of list) text += word + " ";
  return text.trimEnd();
}

function joinWithJoin(list) {
  return list.join(" ");
}

// One call is far below a millisecond, so each sample times 300 calls.
const options = { warmup: 20, runs: 21, batch: 300 };
const plus = timeRuns(joinWithPlus, words, options);
const join = timeRuns(joinWithJoin, words, options);

console.log(`results agree: ${plus.result === join.result}`);
console.log(`runs each: ${plus.times.length}, ${join.times.length}`);
console.log(
  `median inside range: ${[plus, join].every(m => m.times[0] <= m.median && m.median <= m.times.at(-1))}`
);

// Timings vary from run to run, so they are reported, not asserted.
// console.error keeps them apart from the checked output above.
console.error(`+= median ${plus.median.toFixed(4)} ms, join median ${join.median.toFixed(4)} ms per call`);
console.error(
  plus.median > 0 && join.median > 0
    ? `ratio (+= / join): ${(plus.median / join.median).toFixed(2)}`
    : "a median is 0: raise batch until every sample is well above the timer's resolution"
);
Text
results agree: true
runs each: 21, 21
median inside range: true

Each sample times 300 calls, about 11 ms of work in Node, so the timer's step of roughly 0.1 ms in a browser is about 1% of a sample instead of more than the whole of one call. Dividing by batch turns each sample back into a per-call time that can be compared across batch sizes. The warm-up calls keep the engine's first, slower calls out of the samples, and the median ignores a few interrupted samples that would drag an average. The three printed lines hold on every machine: the versions agree, each was sampled 21 times, and the median lies inside the range. The ratio goes to console.error because it is an observation, not a value a test can rely on. It also checks for a zero median first, so a batch that is still too short prints advice instead of NaN or Infinity. In Node the two medians were within about 6% of each other (ratios 0.94–0.97), so at 5,000 words neither version needs changing.

Change it and test it

Measure several input sizes locally and save the input size, repetitions and checksum with each result. Compare median timings across repeated runs. Explain why a passing elapsed>=0 check does not validate a performance claim.

Was this article helpful?

Your response is saved on this device.