Buy me a coffee
Chapter 01 · Counting steps01 / 21

Why not just time it?

You wrote a function that finds the largest number in an array, and you want to know if it's fast. The obvious move is to time it. Here the same function scans the same 10 million numbers on three machines.

The stopwatches disagree: about 6 ms on the server, 14 ms on the laptop, 27 ms on the same laptop on battery. A timing describes one machine on one day, not the code.

Now look at the counters. Every machine made exactly 10,000,000 comparisons, one per number. That count belongs to the code itself, so it's what we'll measure.

The timings are illustrative, but the spread is realistic: CPU generation, power settings, other programs and even temperature change clock time. Benchmarks still matter; they just answer a different question.

findMax.jstested on Node 22.22.0
function findMax(arr) {
let max = -Infinity;
for (const x of arr) { // one comparison per element
if (x > max) max = x;
}
return max;
}
 
console.time('findMax');
findMax(numbers); // 10,000,000 numbers
console.timeEnd('findMax'); // ~50 ms on one laptop; yours will differ

Ran it on Node 22.22.0: one timed call over 10 million numbers took tens of milliseconds on an Apple M5 Pro laptop.

Wrong, misleading or unclear? Suggest a fix