Making a Fair Comparison

The profile from the last lesson showed where the match log processor spends its time. Ines, the team’s Python developer, has tidied the step that totals the evening’s points for the Falcons and the Owls. She timed each version once in Python, and the tidy version came out about 15 percent ahead.

Before anyone ships on a number, you need to know whether it means anything. Here you’ll time JavaScript with performance.now() and build a small measurement routine that survives a second look.

Fall Into the Single-Run Trap

The tidy version only renames variables, so any speed difference comes from how you measure. Here’s the JavaScript port, with the Falcons, team 1, and the Owls, team 2, repeated to make 60,000 rows:

Language: JavaScript
const rows = [];
for (let n = 0; n < 20000; n += 1) {
  rows.push({ team: 1, points: 3 }, { team: 2, points: 2 });
  rows.push({ team: 1, points: 4 });
}

function totalPoints(rows) {
  let total = 0;
  for (const row of rows) {
    total += row.points;
  }
  return total;
}

function tidyTotalPoints(matchRows) {
  let points = 0;
  for (const matchRow of matchRows) {
    points += matchRow.points;
  }
  return points;
}

console.log(totalPoints(rows), tidyTotalPoints(rows));

Save it as fair.mjs and run node fair.mjs. The counting loop works like Python’s for n in range(20000):, and .push() appends each of its arguments, as .extend() would. Both versions agree:

Language: Program Output
180000 180000

Ines’s Python file holds the same rows as dicts and the same two functions. She timed each with a clock reading before and after one call:

Language: Python
# rows, total_points() and tidy_total_points() as in the port above
from time import perf_counter

start = perf_counter()
total_points(rows)
old_seconds = perf_counter() - start

start = perf_counter()
tidy_total_points(rows)
tidy_seconds = perf_counter() - start

JavaScript’s clock is performance.now(). It counts milliseconds from when the process started, so, as with perf_counter(), only the difference between two readings means anything. Replace the last line of the file with the same pattern:

Language: JavaScript
let start = performance.now();
totalPoints(rows);
const oldMs = performance.now() - start;

start = performance.now();
tidyTotalPoints(rows);
const tidyMs = performance.now() - start;

console.log("old:", oldMs, "tidy:", tidyMs);

The loops differ only in names, so predict what this prints and what changes if you swap the blocks so the tidy version runs first. Run it a few times. One run on Node v26.13.1 printed this:

Language: Text
old: 6.620856000000003 tidy: 2.0472820000000027

At face value, the tidy version is three times faster. With the blocks swapped, the same machine printed old: 2.0647610000000043 tidy: 6.374437. The winner flipped.

In these runs, whichever block ran first paid for something extra. Likely causes include V8, the JavaScript engine inside Node, still compiling and tuning code, some of it in the background, and the garbage collector cleaning up after the 60,000 new rows. One reading can’t tell you which, and here the order, not the code, picked the winner.

In CPython, single-run pairs of the same functions also swap places from run to run, so one pair can’t establish Ines’s 15 percent either. A single run also catches whatever else the machine was doing. Neither return value is used. CPython runs the call anyway, but an optimizing engine may skip work whose result nobody reads.

Warm Up and Take the Median

Python’s timeit.repeat() already repeats the code instead of trusting one reading and returns every duration for you to summarize. Here you’ll report the median, which one slow sample, say from a collector pause, can only nudge to a neighboring value. You’ll also report min and max to show the spread. In Python, Ines would write this:

Language: Python
import statistics
import timeit

samples = timeit.repeat(lambda: total_points(rows), number=1, repeat=7)
print(min(samples), statistics.median(samples), max(samples))

JavaScript’s standard library has no timeit, so you write the loop yourself. This function makes three untimed warmup calls, then times seven calls on the same input, so it suits synchronous work that leaves its input unchanged. It returns the last result for you to print and check, which keeps the work observable, though no timing code can fully stop an engine from skipping pure work:

Language: JavaScript
function measure(work, input) {
  let result;
  for (let n = 0; n < 3; n += 1) {
    result = work(input);
  }
  const samples = [];
  for (let n = 0; n < 7; n += 1) {
    const start = performance.now();
    result = work(input);
    samples.push(performance.now() - start);
  }
  samples.sort((a, b) => a - b);
  return { result, median: samples[3], min: samples[0], max: samples[6] };
}

Without the comparator in samples.sort((a, b) => a - b), .sort() compares numbers as strings, putting 10 before 9. A negative return puts a first, so this sorts in ascending order like Python’s sorted(). Then samples[3] is the median, and result alone is shorthand for result: result.

Add measure() to fair.mjs, then replace the timing lines with two calls to it:

Language: JavaScript
console.log("old:", measure(totalPoints, rows));
console.log("tidy:", measure(tidyTotalPoints, rows));

On the same machine and Node v26.13.1, one run printed this:

Language: Text
old: {
  result: 180000,
  median: 0.7387110000000021,
  min: 0.6278609999999958,
  max: 0.9356210000000047
}
tidy: {
  result: 180000,
  median: 0.675970999999997,
  min: 0.5857600000000005,
  max: 0.811271000000005
}

Both medians sit well under the single-run readings, as the warmup absorbed the first-call costs. The tidy median is about 8 percent lower, but the spreads overlap: the tidy version’s slowest call, 0.81 milliseconds, took longer than the old version’s median. Swap the two measure() calls and rerun a few times. Six runs on the same machine gave these medians in milliseconds:

Language: Text
old first:   old 0.76  tidy 0.67
old first:   old 0.77  tidy 0.72
old first:   old 0.82  tidy 0.88
tidy first:  old 0.67  tidy 0.69
tidy first:  old 0.74  tidy 0.84
tidy first:  old 0.68  tidy 0.74

Whichever ran second won five times out of six, the same position effect on a smaller scale. Neither version wins consistently, so there’s no speedup to claim.

The timeit analogy has limits. timeit.repeat() switches off Python’s automatic cyclic collection, though reference counting still frees objects, and it times the very first call. measure() leaves the collector running and doesn’t time its warmup calls. Three warmups don’t promise that the engine has finished optimizing, either. You’ll explore the engine’s role in a later lesson.

Keep Correctness Separate From the Clock

Ines’s real question is whether the tidy version is safe to ship, and that has an exact answer. Both versions must return 180000 for this input, every time, on every machine. A test checks that fixed output, never a millisecond count, which changes with the machine, the load, and the Node version.

So a timing report should say what produced it. As in the profiling lesson, process.versions names the runtime:

Language: JavaScript
console.log("node", process.versions.node, "v8", process.versions.v8);

One run on the machine used here printed this. Your versions will likely differ:

Language: Text
node 26.13.1 v8 14.6.202.34-node.40

In the profiling program from the last lesson, the scan checks up to 200 teams for each of 50,000 rows, making 5,025,000 comparisons, while the indexed version makes 50,000 Map lookups, a hundred times fewer. Yet one seven-run report on Node v26.13.1 showed medians of about 4.8 and 0.9 milliseconds, only a fivefold speedup. A work count explains a speed gap but doesn’t guarantee its size.

The JavaScript way, then, is to profile the real program first, check its output against a fixed expected value, and use measure() only to compare versions that already pass. Report the median with its min and max, the Node and V8 versions, and the input size. Believe a difference only if it survives a swapped order and a rerun, and never turn a timing into a pass-or-fail threshold.

In the next exercise, Reconcile the Evening Scores, you’ll total a fresh batch of evening rows for two other teams, keep the teams in first-seen order, and count the lookups your code makes. The exercise checks your code’s totals, order, and lookup count, never its timing.

Become a Member to join the conversation.