Courses / Node.js: From First Script to Production / Chapter 16
Module 7 · Memory and performance · Chapter 16 of 27
Profiling Node: CPU Profiles, Flame Graphs and Load Tests
Builds on Inside the Event Loop: Phases, Timers and setImmediate and V8 Memory, Garbage Collection and Leaks. Next up: Production APIs: Validation, Error Shapes, Idempotency and Fastify.
Part 1 · Measure before you optimise
Why a guess is not a measurement
A slow endpoint is a guess until you measure it.
Programmers are poor at guessing where time goes. The loop that looks expensive is often cheap, and a one-line call can hide most of the cost. Profiling means measuring where a running program spends its time or memory, so that you change the part that matters. The rule that follows is simple: measure, change one thing, measure again. If the second measurement does not improve, the change did not help, whatever you believed.
Three kinds of measurement come up in a Node service, and they answer different questions.
| Tool | Question it answers | Where it is used |
|---|---|---|
| A timer around a call | how long did this one thing take | quick checks, tests |
| A CPU profile | which functions was the CPU busy in | finding the hot code |
| A load test | how does the service behave with many clients | throughput and latency numbers |
A timer is the simplest of the three, and it has traps of its own. The CPU profile and the load test come next.
Timing a function with perf_hooks
performance.now() returns a high-resolution time in milliseconds, with fractions. Take one reading before and one after. Subtract. That works, but it mixes timing code into your logic. performance.timerify(fn) wraps a function so that each call is measured, and a PerformanceObserver receives the entries. The script times the same function five times.
import { performance, PerformanceObserver } from 'node:perf_hooks'; function sumOfSquares(n) { let s = 0; for (let i = 1; i <= n; i++) s += i * i; return s; } const timed = performance.timerify(sumOfSquares); const obs = new PerformanceObserver((list) => { for (const e of list.getEntries()) { console.log(e.name, '(n =', e.detail[0] + ') took', e.duration.toFixed(3), 'ms'); } }); obs.observe({ entryTypes: ['function'] }); for (let run = 0; run < 5; run++) timed(1_000_000); setTimeout(() => obs.disconnect(), 100);
sumOfSquares (n = 1000000) took 2.661 ms sumOfSquares (n = 1000000) took 0.668 ms sumOfSquares (n = 1000000) took 0.686 ms sumOfSquares (n = 1000000) took 0.672 ms sumOfSquares (n = 1000000) took 0.679 ms
Node 24.18.0. Timings vary from run to run.
Each entry is one call. The first took about 2.7 ms and the other four about 0.67 ms, the same work in a quarter of the time. Nothing changed in the code. Most of the gap is warm-up. The first call started in the interpreter, and V8 compiled the function as it became hot, as the memory chapter described, so the later calls ran on faster code.
That is the first trap of microbenchmarks, which time a tiny piece of code in isolation. The first run includes warm-up. The fix is to run the code many times, throw away the first few results, and look at the spread, not at one number.
Other traps
- Noise. Another process, a garbage collection or a power-saving mode can double one reading. Repeat the measurement, and compare medians or percentiles.
- Measuring the wrong thing. A function that takes 2 ms in a loop can take 20 ms when a request passes through it, because of cold caches, a database call or other requests ahead of it. Measure at the level you care about, and that is usually the request.
- Different data. A benchmark on ten records tells you little about ten million. Use data of the size and shape you expect in production.
- Changing two things at once. If you replace a library and a data structure together, you will not know which one helped.
- Clever code. An optimisation that makes code hard to read must earn its place with a number. Tuning a function that is 1 per cent of the total time cannot give you more than a 1 per cent gain.
A request has a shape too. Your service is not "slow" in general. A particular endpoint is slow, for particular inputs, at particular percentiles. Pin that down first. Write down the number you have and the number you need, for example "p99 under 100 ms at 200 requests a second". Then you know when to stop.
Why was the first call in the timerify run four times slower than the rest?
- It ran before V8 had compiled the function to optimised code. Warm-up is part of any first measurement, so benchmarks discard the first few runs.
A function takes 0.3 ms in a benchmark, but the endpoint that calls it is slow. What do you do?
- Measure the endpoint. The function may not be the cost, so profile the whole request and look for where the time actually goes.
You have a change that "should" make a service faster. What must you have before you merge it?
- A before and an after measurement, taken the same way on the same data, showing an improvement that is larger than the run-to-run noise.
Part 2 · CPU profiles and flame graphs
What a CPU profile is
When a measurement says "the service is busy", you need to know in which code. A CPU profile answers that.
A CPU profile is made by a sampling profiler. Every millisecond or so, it records which function is running and the chain of callers above it. After a few thousand samples, the functions that were on top most often are the ones that cost the most time. This is cheap enough to switch on for a real run. Node has one built in. --cpu-prof starts the V8 profiler at start-up and writes a .cpuprofile file when the process exits. The sampling interval is 1,000 microseconds unless you change it with --cpu-prof-interval. The file is named CPU., then the date, time, process id, thread id and a sequence number, and --cpu-prof-dir chooses where it goes.
Two ideas matter when you read one. Self time is time spent in a function's own code. Total time also counts everything it called. A function with a large total time but a small self time is just a caller. The one with a large self time is where the work happens.
A flame graph draws the same data. Each box is a function, boxes are stacked with callers below and callees above, and the width of a box is the share of samples it appears in. A wide box at the top, with nothing above it, is a hot spot. VS Code opens a .cpuprofile file in its built-in profile viewer, which has a table of functions and a flame view.
Profiling a script
The target below parses 200,000 order lines, validates each with a regular expression and computes a checksum. Three small functions are called from main.
function parseRow(line) { return line.split(',').map((cell) => cell.trim()); } function isValid(row) { return /^[a-z]+-\d+$/.test(row[0]) && Number(row[2]) > 0; } function checksum(text) { let h = 0; for (let i = 0; i < text.length; i++) { h = (h * 31 + text.charCodeAt(i)) >>> 0; } return h; }
The first half of l2-target.mjs.
function main() { const lines = []; for (let i = 0; i < 200_000; i++) { lines.push(`order-${i}, Asha ${i % 97}, ${i % 500}`); } let good = 0; let sum = 0; for (const line of lines) { const row = parseRow(line); if (isValid(row)) good++; sum = (sum + checksum(line)) >>> 0; } return { good, sum }; } const r = main(); console.log('valid rows:', r.good, ' checksum:', r.sum);
The second half.
node --cpu-prof l2-target.mjs node top.mjs CPU.*.cpuprofile
You can read the profile file yourself. It is JSON with a list of nodes, each holding a callFrame with the function name, plus samples (the node that was running at each sample) and timeDeltas (the microseconds between samples). The helper adds the time of each sample to the function it landed in and prints the largest.
import fs from 'node:fs'; const profile = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); const byId = new Map(profile.nodes.map((n) => [n.id, n])); const self = new Map(); profile.samples.forEach((id, i) => { const f = byId.get(id).callFrame; const key = (f.functionName || '(anonymous)') + ' ' + f.url.split('/').pop() + ':' + (f.lineNumber + 1); self.set(key, (self.get(key) ?? 0) + profile.timeDeltas[i]); }); const total = [...self.values()].reduce((a, b) => a + b, 0); const top = [...self].sort((a, b) => b[1] - a[1]).slice(0, 7); for (const [key, us] of top) { console.log((us / 1000).toFixed(0).padStart(6), 'ms', (100 * us / total).toFixed(0).padStart(3) + '%', key); }
Reading the result, and what inlining hides
71 ms 34% main l2-target.mjs:17 62 ms 30% parseRow l2-target.mjs:1 38 ms 18% (garbage collector) :0 9 ms 5% (anonymous) l2-target.mjs:1 9 ms 4% (program) :0 8 ms 4% isValid l2-target.mjs:5 3 ms 1% RegExp: ^[a-z]+-\d+$ :0
Self time per function. Times and shares vary a little from run to run.
main has the largest self time, then parseRow, then the garbage collector. The garbage collector shows up as its own entry, which tells you that 18 per cent of the time went on memory management, which fits a script that creates many small arrays and strings.
Where is checksum? It was not listed, although it does real work in a loop. The optimising compiler inlined it: it copied the body into main, so the samples land in main. That is a good thing for speed and a trap for reading. Switching inlining off with two V8 flags brings it back.
91 ms 40% parseRow l2-target.mjs:1 42 ms 18% (garbage collector) :0 31 ms 14% main l2-target.mjs:17 21 ms 9% isValid l2-target.mjs:5 11 ms 5% (program) :0 9 ms 4% checksum l2-target.mjs:9 4 ms 2% (anonymous) l2-target.mjs:2
The same script with --no-turbo-inlining --no-maglev-inlining.
Now checksum appears with its own 9 ms and main shrinks. These flags change how the code is compiled, so keep them for experiments. They are only there to see what a profile is attributing to the caller. Notice too that the percentages changed. Any profile is a model, and you should expect the shares to move by a few points between runs.
Node also has an older profiler: node --prof app.js writes a log, and node --prof-process turns it into a text summary with the heaviest functions and a bottom-up tree. It is still useful when you have only the terminal, but --cpu-prof and a graphical viewer is the easier route. For a flame graph from the operating system's own sampler, the Node documentation describes using perf on Linux, or a ready-made tool called 0x.
In a CPU profile, what is the difference between self time and total time?
- Self time is spent in the function's own code. Total time also includes the functions it called. A big total with a small self time means a caller, and the cost is below it.
Part 3 · Load testing an endpoint with autocannon
What a load test tells you that a timer cannot
A profile shows where one process spends its time. It does not show what happens when two hundred clients arrive together.
A load test sends many requests to a running service and records how long each took. Two numbers come out. Throughput is requests completed per second. Latency is the time one request took, from sending to the full reply. Latency is a distribution, not a number, and you describe it with percentiles: p50 is the median, the value half of the requests beat; p99 is the value that 99 per cent beat, so one request in a hundred is slower. The slowest few per cent are the ones users complain about.
autocannon is a load generator written in Node. It opens a fixed number of connections, and on each connection it sends a request, waits for the reply and sends the next. In the command line, -c sets the connections and -d the duration in seconds. It also has a programmatic API, which the scripts here use, so that the output fits on a page. Its CLI table reports the 2.5, 50, 97.5 and 99 percentiles.
Why connections matter. A single Node process runs your handler code one request at a time. If each request holds the thread for 2 ms and twenty connections each have one request in flight, a new request waits behind up to nineteen others. Latency under load is therefore the handler time multiplied by the queue in front of it. The scene shows it.
Watch for requests B and C waiting while request A holds the thread
Read it as steps
An average that hides the tail
Now see why percentiles matter. This server answers 49 requests in a blink and the fiftieth after a 40 ms busy loop, which stands in for an occasional slow database call or garbage collection.
import http from 'node:http'; let count = 0; http.createServer((req, res) => { count++; if (count % 50 === 0) { const end = performance.now() + 40; while (performance.now() < end) { /* a rare slow request */ } } res.end('ok'); }).listen(55626, '127.0.0.1');
import autocannon from 'autocannon'; const r = await autocannon({ url: process.argv[2], connections: 4, duration: 5 }); const l = r.latency; console.log('requests:', r.requests.total, ' avg latency:', l.average.toFixed(2), 'ms'); console.log('p50:', l.p50, ' p97.5:', l.p97_5, ' p99:', l.p99, ' max:', l.max, '(ms)');
requests: 5949 avg latency: 3.19 ms p50: 0 p97.5: 40 p99: 40 max: 42 (ms)
Four connections, five seconds, on this machine. Autocannon reports whole milliseconds.
The average latency is 3.19 ms, which looks fine. The median is under a millisecond. But p97.5 and p99 are 40 ms, and the slowest request took 42 ms. About one request in fifty held the thread for 40 ms, and the others queued behind it, so more than 2.5 per cent of clients saw a 40 ms response. A dashboard that shows only the average would report a healthy service.
Always report percentiles, and report p99 at the least. A target such as "p99 under 100 ms" says something an average cannot.
Running a fair test
A few rules keep a load test honest.
- Warm up. The first seconds include compilation and cold caches. Discard them, or run longer.
- Test on a quiet machine. On this machine the load generator and the server shared the same CPUs, so they competed. A real test uses a separate machine, and still treats the numbers as relative: compare before and after, not against a number from another environment.
- Use realistic requests. The same URL on every request hits caches that real traffic would not. Vary the inputs.
- Mind the closed loop. By default each connection waits for its reply before it sends another. When the server stalls, the generator stops sending, so a stall is under-counted. Autocannon's
--overallRateoption sends at a fixed rate instead and corrects the latencies for that effect, as its documentation explains. - Check errors. A test where requests failed quickly looks fast. Look at the error and non-2xx counts first.
What does p99 = 70 ms mean?
- Ninety-nine per cent of requests finished in 70 ms or less, and one in a hundred took longer.
In the spiky run the average was 3.19 ms and p99 was 40 ms. Which would you put on an alert, and why?
- The percentile. The average hides the slow requests, while p99 shows what one client in a hundred experiences.
Twenty connections hit a handler that holds the thread for 2 ms. About how long does a typical request take?
- Around 40 ms, since each waits for the others in front of it, roughly the handler time times the number of connections in flight.
Part 4 · A worked case: finding and fixing a slow endpoint
The slow endpoint
One endpoint ties the tools together: the search page of a college fest site that lists the first twenty events in a hall.
The service keeps 5,000 events as a JSON string. Each request parses the string, filters the events by hall and returns twenty of them. The environment variable VERSION picks the version of the code under test: slow is the original, and fast is the fix that we will arrive at.
import http from 'node:http'; const events = []; for (let i = 0; i < 5000; i++) { events.push({ id: i, title: `Fest event ${i}`, hall: `Hall ${i % 12}`, tags: ['music', 'tech', 'dance'].slice(0, 1 + (i % 3)) }); } const stored = JSON.stringify(events); const parsedOnce = JSON.parse(stored); const fast = process.env.VERSION === 'fast'; http.createServer((req, res) => { const hall = new URL(req.url, 'http://x').searchParams.get('hall'); const list = fast ? parsedOnce : JSON.parse(stored); const found = list.filter((e) => e.hall === hall).slice(0, 20); res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(found)); }).listen(Number(process.env.PORT), '127.0.0.1'); if (process.env.LIFETIME_MS) { setTimeout(() => process.exit(0), Number(process.env.LIFETIME_MS)); }
The load test uses 20 connections for 5 seconds against the original.
import autocannon from 'autocannon'; const result = await autocannon({ url: process.argv[2], connections: 20, duration: 5, }); const { latency, requests } = result; console.log('connections:', result.connections, ' duration:', result.duration, 's'); console.log('latency ms p50:', latency.p50, ' p97.5:', latency.p97_5, ' p99:', latency.p99, ' max:', latency.max); console.log('requests/s avg:', requests.average, ' total:', requests.total); console.log('errors:', result.errors, ' non-2xx:', result.non2xx);
PORT=55624 VERSION=slow node events-server.mjs & node bench.mjs "http://127.0.0.1:55624/?hall=Hall%203"
connections: 20 duration: 5.02 s latency ms p50: 43 p97.5: 63 p99: 70 max: 94 requests/s avg: 453.8 total: 2269 errors: 0 non-2xx: 0
Baseline: 20 connections, 5 seconds, on this machine.
The baseline is about 454 requests a second. Median latency is 43 ms and p99 is 70 ms. For a page that returns 20 small records that is poor, and it matches what the previous lesson predicted. If a request holds the thread for about 2 ms and twenty are in flight, each waits for around twenty times that.
Finding the hot code
Profile the slow server while the load test runs. The server exits by itself after 6.5 seconds, which makes Node write the profile. The same helper from the earlier lesson prints it.
PORT=55624 VERSION=slow LIFETIME_MS=6500 \ node --cpu-prof events-server.mjs & node bench.mjs "http://127.0.0.1:55624/?hall=Hall%203" node top.mjs CPU.*.cpuprofile
4556 ms 69% (anonymous) events-server.mjs:12 1482 ms 23% (idle) :0 138 ms 2% writev :0 67 ms 1% (garbage collector) :0 41 ms 1% (anonymous) events-server.mjs:15 33 ms 0% (program) :0 13 ms 0% writevGeneric stream_base_commons:121
Self time over the 6.5 s run. (idle) is time the event loop spent waiting.
The request handler, the anonymous function on line 12 of the file, accounts for 69 per cent of all samples and 4.5 seconds of CPU. Waiting for work, shown as (idle), is 23 per cent, about 1.5 seconds. That is mostly the time before the test started and after it ended, so while the test ran the process was busy almost all the time. Everything else is small.
Our summary names the function and not the line, and the handler calls three things: JSON.parse, filter and JSON.stringify. None of them has an entry of its own here, so their time is counted in the handler. So confirm the suspect with a direct measurement, as the first lesson advised.
const events = []; for (let i = 0; i < 5000; i++) { events.push({ id: i, title: `Fest event ${i}`, hall: `Hall ${i % 12}`, tags: ['music', 'tech', 'dance'].slice(0, 1 + (i % 3)) }); } const stored = JSON.stringify(events); const parsed = JSON.parse(stored); function time(label, fn) { const runs = 200; const t = performance.now(); for (let i = 0; i < runs; i++) fn(); console.log(label.padEnd(20), ((performance.now() - t) / runs).toFixed(3), 'ms per call'); } time('JSON.parse', () => JSON.parse(stored)); time('filter and slice', () => parsed.filter((e) => e.hall === 'Hall 3').slice(0, 20)); console.log('stored text:', Math.round(stored.length / 1024), 'KB');
JSON.parse 1.675 ms per call filter and slice 0.029 ms per call stored text: 381 KB
Average of 200 calls each.
Parsing 381 KB of JSON takes 1.7 ms on this machine, and the filter that does the real work takes 0.03 ms. The request spends almost all of its time parsing the same text it parsed on the previous request. That agrees with the profile and with the arithmetic: 20 connections times about 2.2 ms is about 44 ms, the median in the baseline.
The fix, and proving it
The fix is to parse once, at start-up, and reuse the parsed list. In events-server.mjs, that is the line const list = fast ? parsedOnce : JSON.parse(stored);. In the fast version, JSON.parse runs once. The same load test follows.
connections: 20 duration: 5.01 s latency ms p50: 1 p97.5: 3 p99: 3 max: 17 requests/s avg: 10209.21 total: 51044 errors: 0 non-2xx: 0
After the fix, with the same 20 connections and 5 seconds.
Requests per second went from 454 to 10,209. Median latency went from 43 ms to 1 ms, and p99 from 70 ms to 3 ms. The scene lays the numbers side by side.
Throughput gain: ≈ 22 × (10,209 ÷ 454 on this machine)
Read it as steps
The same load test on the same machine, with JSON.parse per request and with one parse at start-up.
The profile of the fixed server, taken the same way, is no longer dominated by one function.
1906 ms 29% (idle) :0 1660 ms 25% (anonymous) events-server.mjs:12 1253 ms 19% writev :0 341 ms 5% emit node:events:456 199 ms 3% (anonymous) events-server.mjs:15 184 ms 3% (program) :0 83 ms 1% parse :0
The fixed server under the same load.
The handler now holds 25 per cent, and the rest is the work of writing sockets (writev) and emitting events. That is what a healthy small server looks like. Further tuning would be a different job, aimed at a different number, and would need to justify itself against the target you wrote down in the first lesson.
Part 5 · Production signals: event loop utilisation, delay and allocation
Watching a service that is already running
A load test happens before release. Once a service is live, you need numbers that say whether it is healthy, without attaching a profiler.
Two numbers are specific to Node, and both come from node:perf_hooks. Event loop utilisation (ELU) is the share of time the event loop spent running code and not waiting. performance.eventLoopUtilization() returns an object with idle, active and utilization. Pass it an earlier reading as well, and it gives the figure for the window between the two. A value near 0 means the process is mostly waiting. A value near 1 means the thread is saturated, so more load can only mean more queueing. It is a good signal for deciding when to add instances.
Event loop delay comes from a timer that repeats at a fixed resolution, 10 ms unless you change it. The histogram records the time between its firings. An idle loop fires on schedule, so it reads about the resolution. A blocked loop fires late and reads more. monitorEventLoopDelay() returns that histogram, and you can ask it for percentiles, in nanoseconds.
The script serves the slow endpoint again and prints both numbers every second. It sits idle for about three seconds. Then the load test runs.
import http from 'node:http'; import { performance, monitorEventLoopDelay } from 'node:perf_hooks'; const stored = JSON.stringify(Array.from({ length: 5000 }, (_, i) => ({ id: i, hall: `Hall ${i % 12}` }))); http.createServer((req, res) => { const rows = JSON.parse(stored).filter((e) => e.hall === 'Hall 3'); res.end(String(rows.length)); }).listen(55625, '127.0.0.1'); const delay = monitorEventLoopDelay({ resolution: 10 }); delay.enable(); let last = performance.eventLoopUtilization(); setInterval(() => { const now = performance.eventLoopUtilization(); const { utilization } = performance.eventLoopUtilization(now, last); last = now; console.log('elu', utilization.toFixed(2), ' delay p50', (delay.percentile(50) / 1e6).toFixed(1), 'ms p99', (delay.percentile(99) / 1e6).toFixed(1), 'ms'); delay.reset(); }, 1000); setTimeout(() => process.exit(0), 9500);
Reading the numbers
elu 0.00 delay p50 15.5 ms p99 16.2 ms elu 0.00 delay p50 15.5 ms p99 16.1 ms elu 0.00 delay p50 15.5 ms p99 16.1 ms elu 0.79 delay p50 15.6 ms p99 23.9 ms elu 1.00 delay p50 15.1 ms p99 19.5 ms elu 1.00 delay p50 15.3 ms p99 19.4 ms elu 1.00 delay p50 17.4 ms p99 25.3 ms elu 0.18 delay p50 15.3 ms p99 18.8 ms elu 0.00 delay p50 15.5 ms p99 16.1 ms
On this machine. The load ran from the fourth line to the seventh.
ELU is the clear signal. It was 0.00 while idle, then 0.79, 1.00, 1.00 and 1.00 while the load ran, and it fell back afterwards. The delay moved less. Its p99 went from 16 ms to between 19 and 25 ms during the load.
Look at the idle line. The delay is not near zero. It is about 15 ms at the median, although the timer was set to 10 ms. The next script measures an idle loop with a 10 ms and a 1 ms resolution, once here on Windows and once on Linux under WSL.
import { monitorEventLoopDelay } from 'node:perf_hooks'; import { setTimeout as sleep } from 'node:timers/promises'; for (const resolution of [10, 1]) { const h = monitorEventLoopDelay({ resolution }); h.enable(); await sleep(2000); h.disable(); console.log('resolution', resolution, 'ms, idle loop: p50', (h.percentile(50) / 1e6).toFixed(1), 'ms'); }
resolution 10 ms, idle loop: p50 15.5 ms resolution 1 ms, idle loop: p50 15.4 ms
Windows, Node 24.18.0.
resolution 10 ms, idle loop: p50 10.1 ms resolution 1 ms, idle loop: p50 1.1 ms
Linux, Node 24.18.0 under WSL.
On Linux the idle reading follows the resolution: about 10 ms, then about 1 ms. On Windows both settings read about 15 ms on this machine, so a timer there cannot repeat faster than about 15 ms. The baseline belongs to the platform, not to your code. That is why you read this metric as a change from its own baseline on the same platform, and not as an absolute number. If it moves from 16 ms to 500 ms, something blocked the loop.
Put both on a dashboard. Alert on ELU staying above about 0.8 for several minutes, and on the delay percentile rising well above its baseline. Combine them with p99 request latency from your access log or metrics system, which the observability chapter covers.
A related signal comes from the heap. Memory leaks and heavy allocation show up in heapUsed, and the memory chapter showed how to chase them with snapshots.
Allocation hot spots with --heap-prof
A CPU profile finds slow code. A heap profile finds the code that allocates memory. --heap-prof starts V8's sampling heap profiler and writes a .heapprofile file when the process exits, with the same naming pattern as the CPU profile. Each node in it has a call frame and a selfSize in bytes. The script allocates three million short-lived objects, which a ring of 100 slots keeps from being optimised away, and then keeps 20,000 larger ones.
const keep = []; const ring = new Array(100); function garbage() { for (let i = 0; i < 3_000_000; i++) ring[i % 100] = { a: i, b: [i] }; } function retained() { for (let i = 0; i < 20_000; i++) { keep.push({ id: i, pad: new Array(50).fill(i) }); } } garbage(); retained(); console.log('kept:', keep.length);
import fs from 'node:fs'; const profile = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); const bySite = new Map(); (function walk(node) { const f = node.callFrame; const key = (f.functionName || '(anonymous)') + ' ' + f.url.split('/').pop() + ':' + (f.lineNumber + 1); bySite.set(key, (bySite.get(key) ?? 0) + node.selfSize); node.children.forEach(walk); })(profile.head); const total = [...bySite.values()].reduce((a, b) => a + b, 0); const top = [...bySite].sort((a, b) => b[1] - a[1]).slice(0, 4); for (const [key, bytes] of top) { console.log((bytes / 1024 / 1024).toFixed(1).padStart(6), 'MB', (100 * bytes / total).toFixed(0).padStart(3) + '%', key); }
7.0 MB 100% retained l5-alloc.mjs:8 0.0 MB 0% (root) :0 0.0 MB 0% (anonymous) :0 0.0 MB 0% run module_job:428
Sampled live allocation per function, from node --heap-prof.
Nearly all of the profile is retained, at about 7 MB in this run. The profiler samples, so the figure moves between runs: 5.5 to 11 MB in the runs here, around the 9.5 MB that the 20,000 objects hold after a forced collection. The function garbage allocated far more objects in total, and it does not appear at all. The profile reports sampled allocations that are still alive when it is written, so it shows what stays in memory and not the churn that the young generation clears. It is the tool to use after a heap snapshot has told you what is growing, to find which code line creates it.
Last, a note on when to stop. Every optimisation costs the next reader some clarity. Once the numbers meet the target you set, such as p99 under 100 ms at the expected load, stop. Keep the load test in your repository, run it before releases, and tune again only when it says you have to.
All chapters · Previous: V8 Memory, Garbage Collection and Leaks