Benchmark two approaches with tinybench
Compare two implementations with tinybench, which warms up, runs each task many times and reports throughput and margin of error instead of one noisy timing.
A single performance.now() pair tells you very little. tinybench runs each function repeatedly, warms it up first, and gives you statistics.
npm install --save-dev tinybenchimport { Bench } from 'tinybench';
const items = Array.from({ length: 1000 }, (_, i) => i);
const bench = new Bench({ time: 500 });
bench
.add('for loop', () => {
let sum = 0;
for (let i = 0; i < items.length; i++) sum += items[i];
return sum;
})
.add('reduce', () => items.reduce((a, b) => a + b, 0));
await bench.run();
console.table(bench.table());┌─────────┬───────────┬────────────────────────┬──────────────────┐
│ (index) │ Task name │ Throughput avg (ops/s) │ Latency avg (ns) │
├─────────┼───────────┼────────────────────────┼──────────────────┤
│ 0 │ 'for loop'│ '1,203,411 ± 0.21%' │ '831 ± 0.21%' │
│ 1 │ 'reduce' │ '1,187,902 ± 0.35%' │ '842 ± 0.35%' │
└─────────┴───────────┴────────────────────────┴──────────────────┘The figures are an example and will differ on your machine; read the two rows side by side, and compare the margin of error before declaring a winner.
Return a value from each task so the engine cannot throw the work away as dead code. A micro-benchmark measures the isolated function, not your application, so confirm any win in a profile of the real thing. See tinybench on GitHub.