CodeBlanks Logo Icon CodeBlanks

Benchmark

Learn to write and compare benchmarks.

What is a benchmark?

A benchmark compares two or more solutions under the same workload. In Node.js libraries like benchmark.js or tinybench do this; the result is measured in operations per second (ops/sec).

A benchmarkLabel(opsPerSec) function labels this result: 1000 and above returns 'fast', 100 and above 'medium', otherwise 'slow'. Example: benchmarkLabel(1500) returns 'fast', benchmarkLabel(50) returns 'slow'. This reduces a raw number to three buckets. Real benchmark tools also handle warmup and statistical spread; we simplify the logic here. When comparing two solutions, both average and consistency matter.

Warmup and consistency

When running a benchmark, warmup matters. In the first few calls V8 has not optimized yet; results look slow. After warmup calls are skipped, measurement starts. Also, take the average and spread of many runs, not a single shot.

Example: benchmarkLabel(1500) returns 'fast'; the post-warmup average is high. If benchmarkLabel(50) returns 'slow', the solution may be bottlenecked. Inconsistent results (1500 in one run, 50 in another) usually come from the garbage collector or system load. This is why benchmark results must always be read with warmup and statistical spread in mind.

Practice Write the benchmark label function

Write function benchmarkLabel(opsPerSec). Add if (opsPerSec >= 1000) return 'fast';, if (opsPerSec >= 100) return 'medium'; and return 'slow';. Print console.log(benchmarkLabel(1500)) and console.log(benchmarkLabel(50)).

Starter code

index.js
// Write the benchmarkLabel function
// 1000 ops/sec or more returns 'fast', 100 or more 'medium', otherwise 'slow'
// Print calls with 1500 and 50
// write here

Sample solution

index.js
function benchmarkLabel(opsPerSec) {
  if (opsPerSec >= 1000) return 'fast';
  if (opsPerSec >= 100) return 'medium';
  return 'slow';
}
console.log(benchmarkLabel(1500));
console.log(benchmarkLabel(50));

Expected output

fast
slow

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does benchmarkLabel(1500) return?

index.js
function benchmarkLabel(o) {
  if (o >= 1000) return 'fast';
  if (o >= 100) return 'medium';
  return 'slow';
}
benchmarkLabel(1500)
  • medium
  • fast Correct answer
  • slow
  • 1500

Explanation: 1500 >= 1000, so it returns 'fast'.

2 Match each piece to its role

Term Meaning
ops/sec Ops per second
warmup Warmup call
fast 1000 and above
slow Below 100

3 Complete the fast branch

Question
if (opsPerSec >= ____) return 'fast';
Answer
if (opsPerSec >= 1000) return 'fast';

Explanation: The threshold for fast is 1000.

All lessons in Expert