Skip to content
jshacks.dev
Performance

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.

1 min read
Summarize in AI

A single performance.now() pair tells you very little. tinybench runs each function repeatedly, warms it up first, and gives you statistics.

Shell
npm install --save-dev tinybench
bench.jsJavaScript
import { 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());
Text
┌─────────┬───────────┬────────────────────────┬──────────────────┐
│ (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.

Also inNode.js
Taggednode 24
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.