Finding the Expensive Work
The match-log processor’s totals are right, but refreshing the standings is slow, and it’s tempting to fix whatever looks slow. Here, you find where the time goes first.
In the report script, report.mjs, Array.from() builds an array of a given length, like a list
comprehension over range(): 200 teams and 50,000 rows. { id } is short for { id: id }, and
the parentheses make the arrow return an object. scanTotal() adds up the points of rows whose
team hasTeam() finds. Each of five refreshes builds a label per team:
const teams = Array.from({ length: 200 }, (_, id) => ({ id }));
const makeRow = (n) => ({ team: n % 200, points: n % 5 });
const rows = Array.from({ length: 50000 }, (_, n) => makeRow(n));
function hasTeam(id) {
for (const team of teams) {
if (team.id === id) return true;
}
return false;
}
function scanTotal() {
let total = 0;
for (const row of rows) {
if (hasTeam(row.team)) total += row.points;
}
return total;
}
for (const refresh of [1, 2, 3, 4, 5]) {
const labels = teams.map((team) => `Team ${team.id}`);
console.log(refresh, scanTotal(), labels.length);
}
Each refresh prints the checksum, 100000, and the label count, 200:
1 100000 200
2 100000 200
3 100000 200
4 100000 200
5 100000 200
In Python, you’d reach for cProfile, python -m cProfile -s tottime report.py, which counts every
call. Node has a profiler built in. The --cpu-prof flag records the whole run and
writes the profile to a file at exit. --cpu-prof-dir names a folder for it, here profiles, and
Node creates the folder if it’s missing. The output doesn’t change, and the file’s name holds the
date, time and process id:
$ node --cpu-prof --cpu-prof-dir=profiles report.mjs
1 100000 200
2 100000 200
3 100000 200
4 100000 200
5 100000 200
$ ls profiles
CPU.20261113.234502.31511.0.001.cpuprofile
Unlike cProfile, this profiler doesn’t count calls. About once a millisecond, it records which
function is running, and the file holds those samples as JSON. Python 3.15’s
profiling.sampling samples too, from outside the process. Chrome DevTools’ Performance panel and
VS Code open the file and show milliseconds per function, about one per sample. Here, a table
counts the samples instead.
Before you open the profile, write down a guess. The labels line looks busiest: an arrow call and
a new string per team, while hasTeam() looks like one plain check. So the guess to write down is
which function gets the most samples, and roughly what share.
The top row is hasTeam(): 19 of 56 samples, about 34 percent. The labels arrow got none. These
counts come from one run on one machine, a Linux VM with 8 vCPUs running Node 26.13.1 and V8
14.6.202.34-node.40, so yours will differ:
| Function | Starts at line | Self samples | Share |
|---|---|---|---|
hasTeam |
5 | 19 | 34% |
| (garbage collector) | 13 | 23% | |
scanTotal |
12 | 10 | 18% |
| Node’s own code (6 functions) | 7 | 12% | |
| top-level code | 1 | 3 | 5% |
| (idle) | 2 | 4% | |
makeRow |
2 | 1 | 2% |
| the row-3 arrow | 3 | 1 | 2% |
| the labels arrow | 21 | 0 | 0% |
Each sample goes to the function on top of the stack. While hasTeam() runs, scanTotal() waits,
so those 19 are hasTeam()’s self samples. They also count toward scanTotal()’s total: 29, 10
of them its own.
Python’s sampler calls these direct and cumulative samples, and cProfile tottime and cumtime.
On the Python version of the report, cProfile also puts has_team() first: 250,000 calls and
0.623 seconds of tottime. Its times come from one run with Python 3.15.2, and the output here is
cut to its column heads and the two report functions:
$ python -m cProfile -s tottime report.py
...
ncalls tottime percall cumtime percall filename:lineno(function)
250000 0.623 0.000 0.623 0.000 report.py:4(has_team)
5 0.051 0.010 0.674 0.135 report.py:10(scan_total)
...
The file even records lines: all 19 were on lines 6 and 7. The labels arrow runs 200 times a refresh, but that check runs up to 200 times for each of 50,000 rows.
Some entries aren’t your code. The garbage collector’s 13 samples came while memory was
reclaimed, with no owner named. Node’s startup and output code took 7, and (idle) means
nothing was running.
Sampling is statistical. One refresh gave only about 35 samples, 5 to 9 in hasTeam(), never more
than the garbage collector. So the script repeats the refresh a bounded
five times: over ten more runs, hasTeam() held 33 to 48 percent, first every time.
Now fix what the profile found. As with a dict or set keyed by id in Python, build a Map from
team id to team once. Each row’s check becomes one .has() lookup, in indexedTotal():
const teams = Array.from({ length: 200 }, (_, id) => ({ id }));
const makeRow = (n) => ({ team: n % 200, points: n % 5 });
const rows = Array.from({ length: 50000 }, (_, n) => makeRow(n));
const byId = new Map(teams.map((team) => [team.id, team]));
function indexedTotal() {
let total = 0;
for (const row of rows) {
if (byId.has(row.team)) total += row.points;
}
return total;
}
for (const refresh of [1, 2, 3, 4, 5]) {
const labels = teams.map((team) => `Team ${team.id}`);
console.log(refresh, indexedTotal(), labels.length);
}
The checksum is still 100000 on every refresh:
1 100000 200
2 100000 200
3 100000 200
4 100000 200
5 100000 200
Profile again: hasTeam() is gone, and the garbage collector and indexedTotal() lead. Here’s
one run on the same machine:
| Function | Starts at line | Self samples | Share |
|---|---|---|---|
| (garbage collector) | 10 | 30% | |
indexedTotal |
7 | 9 | 27% |
| top-level code | 1 | 6 | 18% |
| Node’s own code (5 functions) | 6 | 18% | |
| (idle) | 2 | 6% |
A profile shows where time went, not how much you saved.
So profile first: write the guess down, record a profile, and check it against the samples before
changing code. Report shares as one run’s observation, with the versions. process.versions, a
Node object browsers don’t have, lists them:
console.log(process.versions.node, process.versions.v8);
On the machine above, this line logs Node 26.13.1 and V8, its JavaScript engine:
26.13.1 14.6.202.34-node.40
Next up is the text lesson Making a Fair Comparison, where you’ll time the work with
performance.now(): warmups, repeated measurements and their median, with versions and variation.