Node.js
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.
Exercise 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)).
Show example solution
function benchmarkLabel(opsPerSec) {
if (opsPerSec >= 1000) return 'fast';
if (opsPerSec >= 100) return 'medium';
return 'slow';
}
console.log(benchmarkLabel(1500));
console.log(benchmarkLabel(50));
Test yourself
-
What does benchmarkLabel(1500) return?
function benchmarkLabel(o) {
if (o >= 1000) return 'fast';
if (o >= 100) return 'medium';
return 'slow';
}
benchmarkLabel(1500)
Show answer
fast — 1500 >= 1000, so it returns 'fast'.
-
Match each piece to its role
- ops/sec
- Ops per second
- warmup
- Warmup call
- fast
- 1000 and above
- slow
- Below 100
-
Complete the fast branch
if (opsPerSec >= ____) return 'fast';
Show answer
if (opsPerSec >= 1000) return 'fast';
Next lesson: Production tuning