Performance course · Start here · 28 short lessons, about 10 minutes each
Make it fast: a practical performance course
A quick, self-paced intro to the findings in this list. Proven fixes from open-source projects such as pnpm, React, TypeScript and Vue, taken from the links in awesome-performance-patches and grouped the way that list groups them.
Each lesson teaches 2 or 3 ideas, each with a small worked example and a diagram.
Reflects the list at commit cfaa56c (27 September 2026). Last updated 22 November 2026.
Start now (10 minutes)
Open 01 Is it computing or waiting?. Every lesson stands alone, so you can also jump straight to the symptom you have, using the table further down.
Lessons
Eleven tracks, in the order to read them: measure first, then JavaScript and Node, then the browser, then tools and engine internals.
Small Node scripts in the demos/ folder next to this page. No packages needed. Run them from the course folder, for example node demos/lookup.js.
Demo
Lessons
lookup
03, 07
stages and top-self
01, 02
spread-vs-push
08
serial-vs-parallel
10, 11
entries-vs-forin
12
date-format
05
yield
11, 23
shapes, ic-cliff, deopt
27, 28
Sources
kurtextrem/awesome-performance-patches, README at commit cfaa56c (27 September 2026). 187 links were read; about 20 could not be fetched (mostly X/Twitter and Medium).
Researched and drafted with AI assistance from the linked sources, then reviewed by a human. Numbers come from those sources or from the demos in this folder.
Engine details change between versions. Re-check anything engine-specific on your own Node or browser version before relying on it.
Measure first · Lesson 01 of 28 · about 10 minutes
Is it computing or waiting?
A slow step is either busy computing or sitting idle while it waits for a database or the network, and the two need different fixes. After this lesson you can time each step with two clocks and tell which kind of slow you have.
What you will learn
What wall time and CPU time are, and how comparing them tells computing apart from waiting.
How to time each step of a job, so you fix the slow step instead of the one you guessed.
How can two clocks tell computing from waiting?
The idea
Measure real time and processor time for each step: close together means computing, and processor time far below real time means waiting.
Walk through it
A stopwatch such as console.time() tells you how long a step took, but not why. Two clocks answer the why. Wall time is the real time that passes, like the clock on the wall, and it is what a user waits through. CPU time counts only the moments when the processor is actually running your code.
The course demo has a fetch step that asks a pretend database for 25,000 rows. It waits 400 ms for the answer, then turns the answer into objects. While it waits, the processor has nothing to run, so the CPU clock stops. The wall clock keeps going.
In the first diagram, the long outlined bar is the wall clock and the two thin solid slivers are the CPU clock. Fetch takes about 410 ms of wall time but only 12 ms of CPU time. So for about 97 percent of the step, the processor was idle, which means it had nothing to do.
Look at the gap: the wall clock runs the whole time, but the processor only works in the two solid slivers.
The second diagram puts all three steps of the demo on one scale. The build step matches 20,000 orders to 5,000 customers. It takes about 327 ms of wall time and 322 ms of CPU time, so the processor was busy almost the whole time. The write step, which joins the rows into text, takes about 2 ms.
Compare each pair of bars. Fetch has a long wall bar and a tiny CPU bar (waiting); build has two almost equal bars (computing). Node 22, one machine.
This matters more as a job grows. If a page makes 20 waits of 400 ms one after another, that is 8 seconds of wall time with almost no CPU time. A faster processor would not save one of those seconds, because the processor was never what held it up.
When CPU time is close to wall time, the code is CPU-bound: it is slow because it computes. A profile shows where (lesson 02). When CPU time is far below wall time, the code is I/O-bound. It waits for input and output, such as the network, the disk or a database. Then you cut or overlap the waits instead (lesson 10).
The fix
Wrap each step in a small helper that reads both clocks. performance.now() gives wall time in milliseconds. process.cpuUsage() gives CPU time in microseconds, so the helper divides it by 1,000.
// Before: one clock, so you only learn "slow"
console.time('fetch'); const data = await fetchRows(); console.timeEnd('fetch');
// After: two clocks around any step
async function stage(name, fn) {
const wall0 = performance.now(), cpu0 = process.cpuUsage();
const result = await fn();
const cpu = process.cpuUsage(cpu0); // microseconds since cpu0
console.log(name, 'wall', performance.now() - wall0, 'cpu', (cpu.user + cpu.system) / 1000);
return result;
}
Watch out
process.cpuUsage() counts the whole Node process, including other requests running at the same moment. Measure in a script or on a quiet machine.
CPU time can come out slightly above wall time, because Node also runs helper threads, for example for garbage collection. Read "close" as close.
Evidence
Turning on npm's progress bar once made an install take about 49 seconds instead of 32. About 13 of the extra 17 seconds were CPU time, so the progress bar was computing, not waiting.
The red parts are the extra time the progress bar added. They are almost the same length on both clocks, so the extra time was spent computing. Source: npm issue #11283.
Why time each step instead of the whole job?
The idea
Time every step separately before you change anything, because one total cannot tell you which step to fix, and guesses are often wrong.
Walk through it
The whole demo job takes about 739 ms. That is the sum of its three steps: 410 for fetch, 327 for build and 2 for write. With only the total, you have to guess where the time goes.
A common guess is the write step, because building one big string of text sounds expensive. In the diagram, that guess is the thin sliver at the right end. Even if writing became free, the job would get 2 ms faster, which is less than 1 percent.
Timed per step, the picture changes. Two steps hold almost all the time, and they are different kinds of slow. Fetch is waiting, so fewer or overlapping requests would help. Build is computing, so a profile will show which line keeps the processor busy.
Same 739 ms, two views. The guessed step is the thin red sliver at the right end; the real time sits in fetch and build. Bars are to scale.
Real jobs have 10 or 20 steps, so a guess is even more likely to miss. The slow part is often a small helper nobody suspected, called thousands of times. Timing every step costs a few lines and removes the guessing.
The fix
Replace the single total with one stage() call per step, using the helper from section 1. Then fix the biggest step first, and pick the tool by the two clocks.
// Before: one total for the whole job
console.time('report');
await makeReport();
console.timeEnd('report'); // "report: 739ms", but which part?
// After: one line per step, both clocks each
const data = await stage('fetch', fetchRows);
const rows = await stage('build', () => buildRows(data));
await stage('write', () => writeCsv(rows));
Watch out
Start with the biggest step. Halving a 2 ms step saves 1 ms; halving a 327 ms step saves about 160 ms.
Run the job a few times before you trust a number, because the first run is often slower. Lesson 03 explains why.
Evidence
When the slow npm install was profiled, about 23 percent of the program's time sat in one progress-tracking method. Few people would have guessed it.
Try it
Try it (2 minutes)
From the course folder, run the demo that times each step with both clocks.
node demos/stages.js
Look for fetch at about 410 ms wall but only about 12 ms CPU, which is waiting. Build should show about 327 ms wall and 322 ms CPU, which is computing. Your numbers will differ a little; the gap between the two clocks is what matters.
Remember
Wall time is what users wait through; CPU time is how long the processor actually worked.
CPU close to wall means computing, so profile it. CPU far below wall means waiting, so cut or overlap the waits.
Time every step before you change anything, and start with the biggest one.
Words used in this lesson
Term
Plain meaning
Wall time
The real time that passes from start to end, as a user feels it.
CPU time
The time the processor spent actually running your code.
Idle
The processor has nothing to run, usually because the code is waiting.
CPU-bound
Slow because it is busy computing.
I/O-bound
Slow because it waits for input and output, such as the network, the disk or a database.
Quick check
A report takes 90 seconds of wall time but only 8 seconds of CPU time. Where do you look first?
At the waiting, not the code. The processor was busy for less than a tenth of the time, so a CPU profile would show mostly idle. Count the database queries and network requests, and see which ones can be combined or run at the same time.
A step takes 300 ms of wall time and 295 ms of CPU time. Will a faster database help it?
No. The two clocks are almost equal, so the step is computing for nearly all of its time. A database that answers sooner cannot shorten work the processor is doing; a profile of this step will show where that work is.
Your timer says the whole job takes 2 seconds. Do you know what to fix?
Not yet. A total cannot tell you which step holds the time, or whether that step is computing or waiting. Time each step with both clocks first, then start with the biggest one.
Read more
npm issue #11283: a progress bar that cost CPU, found with a profile.
v8-perf: profile top-down, starting by confirming the time is really in JavaScript.
Measure first · Lesson 02 of 28 · about 10 minutes
Read a flame graph
Once you know a step is computing, you still need to know which function keeps the processor busy. After this lesson you can record a CPU profile and read its flame graph down to the one function worth fixing.
What you will learn
How a sampling profiler works, and why it counts snapshots instead of timing every call.
The difference between total time and self time, and why self time points at the work.
How to walk a flame graph from the widest bar down to the target.
How does a profiler see where the time goes?
The idea
A sampling profiler pauses your program about once per millisecond and notes which functions are running. The function caught in the most snapshots is where the time goes.
Walk through it
The call stack is the chain of function calls active at one moment. In the lesson 01 demo, report calls buildRows, and buildRows calls the find() callback (called "find cb" in the diagrams). While the callback runs, all three are on the stack, and the callback is the one doing the work.
A sampling profiler, such as the one Node starts with node --cpu-prof, does not time each call. About once per millisecond it pauses the program and copies the stack. Each copy is called a sample.
Pretend the profiler took only 10 samples of the demo. In the diagram, samples 1 to 4 land while fetch waits, so no JavaScript is running and the profiler writes down (idle). Samples 5 to 10 land in build. Five of them caught the callback running, and sample 7 caught buildRows itself, between two calls.
Each column is one sample, taken at even intervals. Count the red boxes in the find cb row: the callback was caught running in 5 of the 10 samples.
The real run lasts about 740 ms, so it collects about 740 samples, not 10. The proportions stay roughly the same. A function that runs for 300 ms shows up in about 300 samples, which is why counting samples works as a clock.
The fix
Stop adding timers around hunches. Let the profiler watch every function at once, with no code changes, and open the file it writes in a viewer.
// Before: timers only where you already suspect a problem
console.time('find'); /* ... */ console.timeEnd('find');
// After: sample every function, then open the file
// node --cpu-prof --cpu-prof-dir=/tmp/prof demos/stages.js
// Open the .cpuprofile in Chrome DevTools (Performance panel) or speedscope
Watch out
A CPU profile only sees computing. Waiting shows up as (idle), so an I/O-bound step looks empty rather than slow.
Samples are an estimate. Tiny functions called very often can be missed, and a short run gives few samples, so repeat the action or use bigger input.
Evidence
A profile of one large pnpm install found two functions redoing the same work. Fixing them took the install from about 64 seconds to about 14.
What is the difference between total time and self time?
The idea
Total time counts every sample a function appears in. Self time counts only the samples that caught it running its own lines, so self time points at the work.
Walk through it
A flame graph merges the samples. Matching stack entries are joined into one bar, and each bar's width is the number of samples it appeared in. In DevTools and speedscope, callers sit above the functions they call. Merged views, such as speedscope's Left Heavy, sort the bars, so left to right is not time order. The DevTools Performance panel shows a flame chart instead, which keeps time order.
In the diagram, report is 6 samples wide, because it was on the stack in all six build samples. buildRows is also 6 wide. The callback is 5 wide.
Self time is the part of a bar with nothing underneath. The dashed red slot is the one sample where buildRows ran its own code.
Total time is the full width of a bar. Self time is the part of a bar with nothing underneath it, because those are the samples where that function itself was running. So buildRows has a big total but a small self, and the callback is all self:
Function
Total (samples)
Self (samples)
report
6
0
buildRows
6
1
find callback
5
5
In a real profile with hundreds of functions, the biggest totals belong to the outer callers, such as a request handler. They are wide because everything runs under them, not because their own lines are slow. Sort by self time to find the lines that actually use the processor.
The fix
Make self time easy to read by naming hot callbacks. An arrow function passed inline has no name, so profiles show it as (anonymous). A named function expression shows up under its name.
// Before: appears in the profile as "(anonymous)"
orders.map((o) => customers.find((c) => c.id === o.customerId));
// After: appears as "matchCustomer"
orders.map((o) => customers.find(function matchCustomer(c) {
return c.id === o.customerId;
}));
Watch out
High total with low self means "look further down", not "optimise this function".
Most viewers also show the file and line of each function, which helps when a name is missing.
Evidence
Profiles of one build pipeline showed a regex in a CSS plugin running on every rule. Skipping it in files without the special comments it looks for saved about 4.6 seconds.
Which bar do you fix?
The idea
Start at the widest bar and step down while the bars stay wide. Stop at a wide bar with nothing underneath: its own code is the target.
Walk through it
Real flame graphs have hundreds of bars, so you need a route. The diagram shows an illustrative profile of a server building a report under load. Its top row splits all samples between (idle), handleRequest and the garbage collector, which frees unused memory.
Step 1: pick the widest bar that is not idle. Here that is handleRequest, at about 55 percent of all samples. Step 2: look at the bars directly under it and follow the widest one, buildReport (44 percent), then buildRows (40 percent). Each is still wide, so the time is still further down.
Step 3: matchCustomer is about 34 percent wide and has nothing underneath it. Its self time is its whole width, so its own lines do the work, and it is the target. In the demo, this is the find() callback. It scans up to 5,000 customers for each of 20,000 orders, which is up to 100 million comparisons.
Illustrative profile. Width is the share of samples; callers sit on top. 1: start at the widest bar that is not idle. 2: step down while the bar stays wide. 3: wide with nothing below, so fix this one. The blue outlined bars are the route, the red bar is the target, and the grey bars can wait.
The small grey bars, such as the 4 percent ones beside buildRows and matchCustomer, are cheap to ignore. Even making them free would save only a few percent.
The fix
Fix the target, then profile again. Here the fix is a Map built once, which lesson 07 explains in detail. After the change, the old target should shrink to a sliver, and a different bar becomes the widest.
// Before: each of 20,000 orders scans up to 5,000 customers
const name = customers.find((c) => c.id === o.customerId).name;
// After: build the lookup once; each order is then one direct jump
const byId = new Map(customers.map((c) => [c.id, c]));
const name = byId.get(o.customerId).name;
Watch out
Change one thing at a time and measure after each change, so you know which change helped.
Garbage collector time is real time too. A wide garbage collector bar means the code creates many short-lived objects (lesson 12).
Evidence
The TanStack Start team repeated this loop on one server-rendered page and went from about 430 to about 2,360 requests per second.
One page with 100 links, load-tested on one laptop. Source: the TanStack Start SSR throughput post.
Try it
Try it (3 minutes)
From the course folder, record a profile of the lesson 01 demo, then list the functions by self time.
The second command prints one line per function, largest self time first, like this (one run on Node 22; your numbers will differ):
self ms share function file:line
400 50% (idle)
273 34% (anonymous) stages.js:23
73 9% buildRows stages.js:22
(idle) is the 400 milliseconds of waiting from lesson 01, not work. The real target is stages.js:23: that is the find() callback inside buildRows. Then open the same file in Chrome DevTools or speedscope to see the flame graph itself.
Remember
A profiler counts samples; a function caught in many samples is where the time goes.
Total time includes everything a function calls; self time is its own work. Fix high self time.
Follow the widest bar down to a wide bar with nothing under it, fix it, then profile again.
Words used in this lesson
Term
Plain meaning
Call stack
The chain of function calls active at one moment, from the outer caller to the function running now.
Sampling profiler
A tool that pauses the program at a fixed interval and records the call stack each time.
Sample
One recorded copy of the call stack.
Flame graph
A picture of many samples merged into bars, where a bar's width is how many samples it appeared in.
Total time
All samples where a function was on the stack, including time spent in the functions it called.
Self time
Only the samples where the function was running its own code.
Quick check
A function has a large total time but almost no self time. Should you optimise its body?
No. Total time includes everything it calls, and a low self time means its own lines are cheap. Follow the flame graph down to the function beneath it with high self time, because that is where the processor actually works.
The profile of a slow page is mostly (idle). What does that tell you?
The slow part is waiting, not computing, so a CPU profile is the wrong tool for it. Go back to the two clocks from lesson 01, then count the requests or queries the page waits for.
Why give a hot inline callback a name?
An unnamed arrow function shows up as (anonymous), and a profile can hold many of those. A name makes the self-time list readable at a glance, without looking up each file and line.
Measure first · Lesson 03 of 28 · about 10 minutes
Benchmarks you can trust
A quick timing loop can report a big win that is not real, because the engine and the machine both change what you measure. After this lesson you can spot the three usual traps and set up a comparison whose answer you can believe.
What you will learn
Why the first rounds of a loop run slower than later ones.
How the engine can delete the very work you meant to time.
Why you repeat and alternate runs before you believe a difference.
Why are the first rounds slower?
The idea
The engine speeds code up while it runs, so run some throwaway rounds first and time only the rounds after them.
Walk through it
A benchmark is a small program that times one piece of code, often to compare two versions. Say you wrote a faster price formatter and want proof, so you call it a million times and time the loop.
V8, the JavaScript engine in Node and Chrome, first runs a function in an interpreter. The interpreter starts quickly but runs slowly, because it works through your code one small step at a time. When a function has run many times, the JIT compiler turns it into fast machine code. JIT means just in time: it compiles while the program runs.
In the diagram, each bar is one round of calls. The first rounds are tall because they run in the interpreter. Then the compiled code takes over, and the bars drop and stay low. If you average all twelve rounds, the slow early ones pull your number up.
Illustrative shape. The red rounds are the engine warming up; only the green rounds show the code's real, warmed-up speed.
This hurts short benchmarks most. If each version runs for only a few rounds, one may still be in the interpreter while the other is already compiled. Then you are comparing warm-up, not code.
The fix
Run throwaway rounds before you start the clock, so the timed rounds all run compiled code. This loop still has a second problem, which the next section fixes.
// Before: the clock includes the slow first rounds
console.time('format');
for (let i = 0; i < 1e6; i++) formatPrice(i);
console.timeEnd('format');
// After: warm up first, then time
for (let i = 0; i < 1e5; i++) formatPrice(i); // warm-up, not timed
console.time('format');
for (let i = 0; i < 1e6; i++) formatPrice(i);
console.timeEnd('format');
Watch out
Decide which speed matters. A server runs warm for hours, while a command-line tool that runs once spends much of its life cold.
The compiler tunes code to the inputs it has seen, so warm up with realistic inputs, not one repeated value.
Evidence
The TanStack Start team gave their server a 2-second warm-up before each 30-second load test, so their numbers reflect warmed-up code.
Can the engine skip the work you are timing?
The idea
If nothing uses a result, the compiler may delete the work that produced it, so make every benchmark use its result.
Walk through it
Look again at the loop above. It calls formatPrice(i) a million times and throws every result away. The compiler may notice that the result is never used. If it can also prove the call changes nothing else, it can remove the call. This is called dead-code elimination.
In the diagram, the top row shows what can happen. You wrote a loop with a call in it, but the compiled loop is empty. The timer then measures a million rounds of nothing, and your new formatter looks impossibly fast.
The bottom row keeps the work. Each result is added to a running total, often called a sink, and the total is printed at the end. Now the compiler must run every call, because the printed number depends on all of them.
Read each row from the code down to what the timer sees. When the result is unused, the call can vanish from the compiled code; when it feeds the sink, it must stay.
A useful warning sign: if a benchmark takes about as long as an empty loop, the work was probably removed. Formatting a number into text should cost clearly more than doing nothing.
The fix
Make the output depend on every result. Add something small from each result to a sink, and print the sink once at the end.
// Before: the result is unused, so the call may be removed
for (let i = 0; i < 1e6; i++) formatPrice(i);
// After: every result feeds the sink, and the sink is printed
let sink = 0;
for (let i = 0; i < 1e6; i++) sink += formatPrice(i).length;
console.log(sink); // the output now depends on every call
Watch out
Using the result adds a tiny cost of its own, such as one addition. Do the same thing in both versions, so it cancels out.
bench-node uses results for you, and by default stops V8 from optimising the test function. Its README calls its results "accurate but not realistic", so confirm any win in the real app.
Evidence
bench-node's documentation shows a test flagged at about 4 nanoseconds per run, because an empty function took about 0.8 nanoseconds. Only about 5 times slower than doing nothing is suspicious.
Why repeat and alternate runs?
The idea
Timings wobble from run to run. So repeat each version many times, take turns between them, and let a statistical test decide whether a gap is real.
Walk through it
Noise is the run-to-run wobble that has nothing to do with your code. Other programs, the processor changing speed and garbage collection all shift timings. Run the same code twice and you get two different numbers.
Now compare old code A with new code B, which are really the same speed. You run A four times, then B four times. In the first diagram, a busy spell from another program lands during the B runs only, so B looks slower for no real reason. Alternating A, B, A, B spreads the same spell over both, so the comparison stays fair.
Illustrative. Bar height is the measured time of one run. Look where the amber busy spell lands: on B only at the top, on both A and B at the bottom.
Repeating also gives you a spread of numbers instead of one. In the second diagram, each dot is one run. When the two spreads overlap, you cannot tell A from B. When they sit apart, the difference is real. A t-test is a statistical test that does this check with numbers instead of your eyes.
Illustrative. Each dot is one run; the line shows its range. Only the bottom pair has a gap you can trust.
The fix
Use a small benchmark library instead of a hand-written loop. bench-node repeats each test, compares it with a baseline and, with ttest on, runs a t-test on the gap. The --allow-natives-syntax flag lets it use V8's internal commands, which it needs to control optimisation.
// Before: one run each, all A then all B, read by eye
// After: repeated runs, a baseline, and a test of the gap
const { Suite } = require('bench-node');
const suite = new Suite({ ttest: true }); // is the gap real, or noise?
suite.add('old', { baseline: true }, () => oldFormatPrice(1234));
suite.add('new', () => newFormatPrice(1234));
suite.run(); // run with: node --allow-natives-syntax bench.js
For whole browser pages, Tachometer alternates the two versions in fresh browser runs until it is confident about the gap. For command-line tools, its author points to Hyperfine.
Watch out
Do not stop measuring the moment you see the answer you hoped for. Decide the number of runs before you start.
Measuring tools add their own cost. A TanStack Query pull request claimed 10 to 20 times faster subscriptions from DevTools profiles; its author later found DevTools had inflated the timer cost.
Evidence
Tachometer's author reports that it has repeatedly caught slowdowns as small as about 1 percent.
Try it
Try it (2 minutes)
From the course folder, run the same demo three times in a row.
The code is identical each time, but the numbers shift a little. That shift is noise. A difference between two versions that is smaller than this shift tells you nothing yet.
Remember
Warm up before timing, and decide whether you care about cold or warm speed.
Use every result, or the engine may time an empty loop.
Repeat, alternate and let a test decide, then confirm the win in the real app.
Words used in this lesson
Term
Plain meaning
Benchmark
A small program that times one piece of code, often to compare two versions.
Interpreter
The part of the engine that runs code step by step; quick to start, slow to run.
JIT compiler
The part of the engine that turns busy functions into fast machine code while the program runs.
Dead-code elimination
The compiler removing work whose result is never used.
Noise
Run-to-run changes in timing that have nothing to do with your code.
t-test
A statistical test that says whether the gap between two sets of runs is likely real or just noise.
Quick check
Your new formatter looks 50 times faster, and the timing loop ignores its return value. Do you trust it?
Not yet. With the result unused, the compiler may have removed the call, so you may be timing an empty loop. Feed every result into a sink, print the sink, and measure again.
You ran all the A rounds, then all the B rounds, and B came out 3 percent slower. Is B slower?
You cannot tell. A noisy spell could have landed on the B rounds only. Alternate A and B, repeat many times, and let a t-test say whether 3 percent is bigger than the noise.
You are benchmarking code for a server that runs for days. Should the first rounds count?
No. The server spends almost all its life running warmed-up, compiled code, so the first rounds would only add warm-up time. Throw them away and time the rounds after them.
Read more
bench-node: micro-benchmarks with a baseline, a dead-code check and a t-test.
A page can spend time on work that nobody needs yet, or ever. You can check for work you can skip and move other work to the first time it matters.
What you will learn
Use a quick check to skip a slow call.
Build a value on first use and reuse it while it stays current.
What can you rule out before measuring?
The idea
A quick check can skip an expensive step once you know its result cannot affect the answer.
Walk through it
A chart has six labels, each with a center position along the bottom axis. The chart draws a label only if its center is inside the view and its text fits. To find out whether the text fits, the code asks the browser for its width.
Suppose the visible range is 20 through 40. The six centers are 0, 10, 20, 30, 40 and 50. In the first diagram, the top row measures all six labels and then checks their positions. The bottom row checks each center first, which leaves only three measurements.
Each filled slot is one width read. Read down each position to see which reads the guard skips.
When a page has pending size or position changes, a width read can make the browser calculate those sizes and positions immediately. That is called forced layout. The second diagram shows where that work can enter the measurement, and Lesson 17 explains when it happens.
Follow the left column when layout is pending; red marks extra browser work. The early exit in the right column avoids starting the width read.
With 10,000 candidate labels and 500 centers in view, the same rule leaves 500 width reads on one pass. Real charts may revisit a label, so a count of measurements and a count of points describe different things.
The fix
Return as soon as the center fails the range check. This is an early exit, and the check that causes it is called a guard clause. Candidates that pass still need the original width and fit checks.
const inView = center => center >= 20 && center <= 40;
// Before
const visible = label => {
const width = measureText(label.text);
return inView(label.center) && fits(label, width);
};
// After
const visible = label => {
if (!inView(label.center)) return false;
return fits(label, measureText(label.text));
};
Watch out
Keep the inclusive bounds if labels centered on either edge can appear.
If the product allows a label centered outside the view to overlap it, a center check can hide valid labels.
Evidence
Recharts reported about 55 percent fewer text measurements after adding the position check and delaying size reads until needed.
What can wait until someone asks for it?
The idea
A lazy value is calculated on first use, so an unused value never costs a build.
Walk through it
A file page opens on Details and offers a History tab. The History tab groups changes by date for display. With three changes, a build reads all three and groups them, even if the reader stays on Details.
With 10,000 changes, the page can still show Details before it visits any of them. In the diagram, the vertical line marks when Details is ready. Building on first use moves the grouping past that line and into the first History open.
Compare the ready markers on the same time axis. The final block runs only if someone opens History.
The fix
Build the grouped list inside the open handler and save it for the next open. The ??= operator runs its right side only when the saved value is null or undefined. A second open can render the saved list straight away.
// Before
const groups = groupByDay(changes);
historyButton.onclick = () => renderHistory(groups);
// After
let groups;
historyButton.onclick = () => {
groups ??= groupByDay(changes);
renderHistory(groups);
};
Watch out
The first open now pays for the build, so measure that interaction as well as page load.
When the changes are refreshed, clear the saved groups so the next open builds from the updated list.
Evidence
Chrome DevTools moved about 3.4 seconds of tree building off the load of a large recording by waiting until the views were opened.
Remember
Put the guard before the call it can skip.
Use the cheap check only when it preserves the answer.
Build a lazy value when someone reads it, and clear it when its inputs change.
Words used in this lesson
Term
Plain meaning
Early exit
Stopping as soon as you have enough information to return an answer.
Guard clause
A check that returns before the rest of a function runs.
Forced layout
A read that makes the browser calculate sizes and positions immediately.
Lazy value
A value calculated when code first needs it.
Quick check
With the guard in place, how many widths do you read if all six centers pass?
You still read six. The guard saves work only for labels it can rule out before the width read.
What happens if History opens twice and the changes stay the same?
The first open groups the changes and stores the result. The second open already has a value, so ??= skips the build.
A loop or a refresh can spend most of its time rebuilding the same thing. You can share setup and reuse results while keeping them current.
What you will learn
Move setup outside a loop when its inputs stay the same.
Save and clear a result that several calls can reuse.
What stays the same on every pass?
The idea
When setup uses the same inputs on every pass, do it once before the loop and share what it prepares.
Walk through it
A report shows three dates using the same locale and options. The locale tells JavaScript which language and region to use. The options say which parts of the date to show and which time zone to use.
Each call to toLocaleDateString asks JavaScript to format a date with those settings. It can repeat work to prepare the settings even though only the date changes. Separating setup from formatting lets you ask for that preparation once.
The red blocks in the diagram mark repeated setup. Follow both rows until the third date is done. For 50,000 dates with identical settings, a shared formatter keeps the 50,000 formatting calls and needs just one explicit setup.
Green blocks format the numbered dates. Blue marks the first setup in each row. Sharing the formatter removes the red setup blocks between dates.
The fix
A setup whose inputs stay constant in a loop is loop-invariant. Moving it out of the loop is called hoisting. Create an Intl.DateTimeFormat with the shared settings, then change only the date passed to format.
const options = { dateStyle: 'medium', timeZone: 'UTC' };
// Before
const before = dates.map(date => date.toLocaleDateString('en-GB', options));
// After
const formatter = new Intl.DateTimeFormat('en-GB', options);
const after = dates.map(date => formatter.format(date));
Watch out
Reuse a formatter only for dates that share its locale and options, including the time zone.
A regular expression, or regex, matches a text pattern. With the g flag, a regex remembers where test() stopped. Drop that flag when checking each row for any match.
Evidence
On one machine, the course demo formatted its dates about 70 times as fast with a shared formatter.
How do you reuse a result across calls?
The idea
Save a result under a key you can look up again, and delete the entry when the source changes.
Walk through it
A list shows a plain text preview of each file. Building a preview reads and cleans the file text, so a refresh repeats that work even if the text stayed the same. Start with two files, A and B.
A cache stores results for later use. A Map stores entries as keys and values, so file A's ID can be the key for its preview. In the first diagram, a lookup for A finds an entry, while a lookup for B must build and store its first preview.
Green marks reuse. The arrow from the build step back to the Map shows how the next read of B can reuse its preview.
Now edit file A. Its ID stays the same, so the old preview would still be found. The second diagram shows where to remove the old entry, which makes the next read build from the new text.
Follow key A through the three stages. The edit makes the red entry stale. Deleting it forces a fresh build when A is read again.
If a refresh reads 10,000 files and only one has changed, the list still needs 10,000 lookups. With the other entries still present, just the edited file needs a new preview.
The fix
Saving a function's result based on its inputs is called memoising. Removing a result that has gone stale is called invalidation. Here the key is the file ID, and each successful edit must delete that key.
// Before
const previewFor = file => buildPreview(file.text);
// After
const previews = new Map();
function previewFor(file) {
if (!previews.has(file.id)) previews.set(file.id, buildPreview(file.text));
return previews.get(file.id);
}
const afterSave = file => previews.delete(file.id);
Watch out
If the preview also depends on display settings, include them in the key or clear affected entries when those settings change.
Saved values take memory. Keep the cache scoped to the list or give a long-lived cache a size limit.
Evidence
One author reported page blocking time below about 200 milliseconds after caching a pattern and sharing its replacement function.
Try it
From the course folder, run node demos/date-format.js.
Compare the first two timings, which use the same settings. Look for same result: true to confirm the output agrees.
Remember
Move setup above the loop when its inputs stay the same.
Save repeated results under a key that covers their inputs.
Clear stale entries when the source changes.
Words used in this lesson
Term
Plain meaning
Loop-invariant
Uses the same inputs on every pass through a loop.
Hoisting
Moving work above the loop that would repeat it.
Cache
A place to keep results for later use.
Memoising
Saving a function's result for the same inputs.
Invalidation
Removing a saved result because it may be stale.
Quick check
Can dates in two different time zones share this formatter?
Each time zone needs its own formatter. The formatter holds the zone as part of its settings, and the same instant can fall on a different date in another zone.
Why clear a preview if a file edit leaves its ID unchanged?
The ID can still find the cached preview, which contains the old text. Removing that entry means the next read has to build from the edited file.
A call that fits on one line can do a surprising amount of work when it runs for every item. You can spot unnecessary work inside calls and share setup when it makes sense.
What you will learn
Spot the work hidden in path and URL helpers.
Decide when a failure needs a record of its callers.
Group small calls so they share one setup.
When is a short call doing extra work?
The idea
Keep the work a built-in does when you need its rules, and skip it when your inputs already satisfy them.
Walk through it
A file exporter generates names from a fixed folder and file numbers. path.join puts the parts together and normalises the result, which means it cleans up things like repeated separators and parent steps. A parent step written as .. goes back up one folder.
On a system that uses slashes, both cases in the diagram begin in the files folder. Only the second case has a parent step to remove. For 10,000 generated paths with simple parts, that is 10,000 cleanups with nothing to change.
The input parts appear above each pair of outputs. Both joins agree for clean parts. The red outline marks the parent step left by the plain join.
new URL also reads and normalises text to produce a structured value. TanStack Router could skip that work when it already had a suitable link and no rule for rewriting it. The query is the part after the question mark. In the diagram below, watch what gets rebuilt as three query values are added.
Each box builds the text after the question mark. The red boxes show intermediate builds. The separate list builds the text once after the last append.
React Router built a separate URLSearchParams collection and assigned the finished query text once. The separate collection holds the name and value pairs without updating a URL on each append. With thousands of values, this avoids rebuilding the growing query again and again.
The fix
For generated paths, join clean parts with the system's separator, path.sep. For a URL, keep the built-in when you need its parsing or normalisation rules.
import path from 'node:path';
// These two parts always contain plain names.
const parts = ['files', 'a.txt'];
// Before
const cleaned = path.join(...parts);
// After
const joined = parts.join(path.sep);
// Before: each append rewrites url.search
for (const v of values) url.searchParams.append('id', v);
// After: build the query once, assign it once
const query = new URLSearchParams();
for (const v of values) query.append('id', v);
url.search = query.toString();
Watch out
Leave path cleanup in place when parts may be empty or contain separators or parent steps. Validate untrusted paths separately.
Reusing URL text needs the same care. A URL starting with two slashes can name another host.
Evidence
In Nitro's code generation benchmark, joining clean path parts made the run about four times as fast.
What does a new Error capture?
The idea
Use an ordinary result for an expected outcome when the caller needs a message and can handle it directly.
Walk through it
A file importer checks rows for a missing name. The caller marks each incomplete row and continues. In Node's JavaScript engine, creating an Error can capture a stack trace, which records the chain of function calls that led there. Each entry is called a frame.
Suppose three rows fail inside checkRow, called from readRows, which was called by importFile. Each column in the diagram is a failed row. Each captured list repeats the same chain, and the caller uses only the message.
Each red block is a captured frame. The green blocks are the messages, which let the caller mark all three rows either way.
If 10,000 rows fail and the engine captures those three calls each time, it records 30,000 frames. A result object keeps the message and the failure flag.
The fix
Return a result so the caller can handle a missing field without constructing an Error. Both versions here return a value the caller checks.
Keep errors when you need the stack to diagnose a failure. Update callers if they used to expect an Error object.
Error.stackTraceLimit caps the number of frames in engines that support it. Changing it affects other code too, and shorter traces can hide useful callers.
Evidence
React cut render time by about 70 percent in one large development-mode test by capturing fewer frames per error.
What if small calls share one setup?
The idea
When several pieces can go out together, send them through a single call and pay its setup cost once.
Walk through it
Suppose an export already has three pieces of text, A, é and !. Encoding turns text into bytes so it can be stored or sent. TextEncoder.encode produces bytes in a standard encoding called UTF-8.
The top row of the diagram sets up an encoding call for each piece. The bottom row joins the pieces and then sets up one call. Both rows convert the same text and send the same bytes in order.
The green blocks give the same bytes in the same order. Blue marks the join and the first setup. Batching removes the two red setup steps.
With 10,000 ready pieces, groups of 100 reduce the number of calls to 100. The amount of text to convert stays the same. Making each call handle several pieces is called batching.
The fix
Collect a group of fragments that the receiver can consume as one piece. Join them without adding a separator, then encode the group.
const encoder = new TextEncoder();
const parts = ['A', 'é', '!'];
// Before
const separate = parts.map(part => encoder.encode(part));
// After
const batch = encoder.encode(parts.join(''));
Watch out
A larger batch may hold more memory and delay the first bytes. Batch pieces you can send promptly.
A surrogate pair is the two string units JavaScript uses for some characters. If fragments split the pair, separate calls encode two replacement characters, while the joined call encodes the original character.
Evidence
Astro's benchmark of a page with many small links saw average response time drop by roughly half after batching encoding.
Remember
Check which rules a short call applies before removing it.
Use stack capture where the chain of calls is useful.
Batch work when the receiver can consume the combined output.
Words used in this lesson
Term
Plain meaning
Normalise
Clean up a value using a standard set of rules.
Stack trace
A list of calls that led to the current point in the code.
Frame
An entry in a stack trace for one call.
Encoding
Converting text to bytes using a defined format.
Batching
Grouping pieces of work so one call can handle them together.
Quick check
Can you replace path.join if a part can be a parent step?
Keep path.join if you need the same normalised path. Plain joining leaves the parent step in the output, as the second row shows.
Why can batching help even when the output bytes stay the same?
Each call prepares the conversion before it turns text into bytes. The batch still converts all the text, but there are fewer calls to set up.
Data structures · Lesson 07 of 28 · about 10 minutes
Index your lookups
Looking up a customer for every order can mean reading the same list over and over. You can build an index, a collection that speeds up lookups, or use a simple check for short lists.
What you will learn
Count the work that find() repeats and build a Map once.
Use a Set for repeated yes or no checks, and keep tiny lists as arrays.
Why is find() inside a loop slow?
The ideaBuild a lookup by customer ID once so every order can use it.
Walk through it
You have four orders and five customer records, in order from A to E. Each order stores a customer ID, and all four orders in this example belong to E.
For the first order, find() compares the ID with A, then B, C and D, before matching E. Starting from the beginning each time is a linear scan.
Each row of the grid starts over, so four orders take twenty comparisons. With ten thousand orders and ten thousand customers, you can reach one hundred million comparisons if every match is last.
Each square is a comparison. The same four wrong IDs get checked again for every order.
The fix
A Map stores a value under a key, which here is the customer ID. Build it from the customer list once, then call get() with the ID on each order.
In a typical implementation, the engine computes a hash, a number based on the key, to choose a small group called a bucket. The next diagram follows E into its bucket, where the engine can check the actual keys and return E's record.
The hash skips bucket one. The key comparison inside bucket two picks E when two IDs share the bucket.
find() returns the first match, while this Map keeps the last record for each key. Use unique IDs or keep the first entry explicitly.
The index takes memory. Rebuild or update it when records are added, replaced, removed, or given new IDs.
Evidence
Building an index by folder path saved pnpm about 35 seconds in the dependency graph step on its test project.
Do you only need a yes or no answer?
The ideaUse a Set for repeated checks against a long list, and start with an array for a short one.
Walk through it
Suppose you check whether incoming tags are on a list of hidden tags. This is a membership check, which asks whether a value is in a collection.
To check draft, includes() compares it with test first, then sample, then draft. For public, it checks all three and answers no.
With a thousand hidden tags, a miss can take a thousand comparisons. A Set stores unique values and can use the same kind of bucket lookup as a Map.
The diagram follows two queries down both paths. The array starts again at test, while both Set queries reuse the collection built from the three tags.
The array starts at the first tag for each query. Red dots miss and the green dot matches. Both queries use the same Set built from the three tags.
The fix
Keep includes() when there are only a few tags or when you check them once. When many lookups share a long list, build the Set before the loop and use has().
// Before
const visibleByScan = tags.filter((tag) => !hiddenTags.includes(tag));
// After
const hidden = new Set(hiddenTags);
const visibleBySet = tags.filter((tag) => !hidden.has(tag));
Watch out
Building a Set reads the entire list and takes extra space. A short scan can be cheaper than building or consulting a separate collection.
If you only iterate over values that are already unique, an array is enough. Growing a hash table can also require moving entries into new buckets.
Evidence
In Valibot’s repeated checks against three keys, both versions took about 110 milliseconds, so it switched to an array.
Try it
From the course folder, run node demos/lookup.js. Check that both versions print the same result and compare their timings, including the time to build the Map.
On one machine, repeated scans took about seventy times as long. Run it twice to see how much your own timings vary.
Remember
find() starts the search over for each order.
Build a Map once when many lookups need a value by key.
Use Set.has() for repeated checks on a long list and includes() on a tiny one.
Words used in this lesson
Term
Plain meaning
Index
A collection built to make lookups faster.
Linear scan
A search that checks entries one at a time.
Key
The value you use to look something up.
Hash
A number computed from a key to choose where to look.
Bucket
A group of keys that a lookup checks after hashing.
Membership
Whether a value is in a collection.
Quick check
How many comparisons do four orders take if their customer is always first?
Four comparisons are enough because each find() stops at the first match. Building a Map would still visit all five customers during setup.
What would you use for a fixed list of three hidden tags?
Start with an array and includes(). Even a miss needs only three comparisons, so a separate collection may offer little benefit.
Data structures · Lesson 08 of 28 · about 10 minutes
Growing and draining lists
Adding a row or taking the oldest job can make JavaScript revisit a whole list. You can build a list by appending and drain one by keeping track of the next job.
What you will learn
Count the copies that spread makes and see when push() needs to copy.
Take jobs in arrival order and reclaim the space used by completed jobs.
Why does copying an array in a loop get slow?
The ideaAppend rows to one array you own so most additions write just one slot.
Walk through it
Six rows arrive one by one. Each time you write [...previous, row], the three dots, called spread, put all previous entries into a new array.
For object rows, spread copies the references, which are links to the same objects. The whole row stays where it was, but each link still takes a slot to write.
Adding the first row copies nothing. Adding the second copies one reference, and adding the sixth copies five. Add the red slots in the diagram to get fifteen copies.
With 50,000 rows, the first addition copies zero entries and the last copies 49,999. The average is about 25,000 copies per addition. Multiply by 50,000 additions to get roughly 1.25 billion copies.
Each row is a new spread result. On pass six, five previous references are copied before the new row is written.
The fix
Start with one array and call push() for each row. JavaScript engines can reserve spare room, called capacity, so later pushes can write into an open slot.
When that space fills, the engine may move the entries into a larger block. The diagram shows two possible growth steps. The fifth push copies entries and the sixth uses a spare slot. The exact sizes vary by engine.
Capacity grows from four slots to eight, then sixteen. Red marks copied entries, green marks entries written by these pushes, and blue marks entries already in place.
// Before
const copied = rows.reduce((previous, row) => [...previous, row], []);
// After
const collected = [];
for (const row of rows) collected.push(row);
Watch out
Append to an array your function created. For a shared array such as React state, make one copy first if the original must stay intact.
concat() can read all earlier entries again, so replacing spread with a different copying method keeps the same growth problem.
Evidence
Appending to local arrays saved about 30 seconds in the TanStack Table author's grouping example.
How can you take the oldest job without moving the rest?
The ideaAdvance the position of the next unread job so waiting jobs stay in their slots.
Walk through it
A queue gives you jobs in the order they arrived. Imagine jobs A, B, C and D waiting, with A at the front.
Calling shift() returns A and lowers the position of every waiting job by one. The top of the diagram shows all three position changes.
With a head index, the number of the next unread slot, you read A and advance that number from zero to one. B is still in slot one.
Engines can optimise small arrays. With a hundred thousand waiting jobs, repeatedly removing the first slot can be much slower than advancing a number.
The red arrows track jobs that change slots after shift(). In the bottom row, the head moves to B and the green outlines show the jobs that stay in place.
The fix
For a batch you read once, loop from the first slot to the last. This reads the same jobs in order and leaves the original array intact.
// Before
while (jobs.length) processJob(jobs.shift());
// After
for (let head = 0; head < jobs.length; head++) {
processJob(jobs[head]);
}
For a queue that keeps receiving jobs, append with push(), keep head between reads, and clear the slot as soon as you take a job. Once half the slots are used, keep just the unread part. This occasional cleanup is called compaction.
if (head * 2 >= jobs.length) {
jobs = jobs.slice(head);
head = 0;
}
Watch out
Set a consumed slot to undefined so the queue stops holding that job. Check head === jobs.length to tell when the queue is empty.
Use shift() when the queue stays short and simple removal meets your needs.
Evidence
On one machine, draining the demo's large queue with shift() took about 200 times as long as reading by index.
Try it
From the course folder, run node demos/spread-vs-push.js. Compare the first two timings for grouping, then the last two for draining the queue.
Before you run it, predict which group is most expensive to copy. The demo puts most rows into the same group, where spread copies more on each pass.
Remember
Spreading a growing array copies its earlier entries on every pass.
push() can reuse spare slots in a local array.
A head index keeps waiting jobs in place, and compaction reclaims used slots.
Words used in this lesson
Term
Plain meaning
Spread
Three dots that expand existing array entries into a new array in this example.
Capacity
The room reserved for entries, including slots still free.
Queue
A collection that gives you the oldest waiting job first.
Head index
The position of the next unread job.
Compaction
Keeping the unread part and dropping the used slots.
Quick check
How many previous entries does spread copy when you add the sixth row?
It copies five references, because there are five rows in the old list. It also writes a slot for the sixth row in the new list.
Why clear a processed slot if the head already moved past it?
Advancing the head changes where future reads start. The array still holds a reference to the old job until you clear that slot or drop it.
Data structures · Lesson 09 of 28 · about 10 minutes
Pack data tightly
When you keep thousands of records, their fields can take up space and scatter the values you read together. You can pack yes or no fields together and keep frequently read numbers side by side.
What you will learn
Store several true or false values in one number and read them back.
Keep numeric fields in separate arrays and use a matching position to read a record.
How can one number store several answers?
The ideaGive each yes or no field its own digit in a number written in base two.
Walk through it
A note can be archived, starred, pinned, or unread. An object can store four separate booleans, which are values that are either true or false.
A bit is one digit in base two, so it can be zero or one. A bit flag uses that digit to store one true or false answer.
Read the first diagram from right to left for the bit values. Unread is worth one and starred is worth four. Both are on, so this note's four flags fit in the number five.
With a hundred thousand notes, four separate boolean fields mean four hundred thousand stored field values. Packing them means each note stores one number.
Each field has a fixed position. The green digits are on, so their values add up to five.
The fix
Name each flag and use |, called bitwise OR, to combine them. It keeps a bit on if either input has that bit on.
The number that selects a bit is called a mask. To test STARRED, use &, called bitwise AND, which keeps a bit only if both inputs have it on. The second diagram shows why the result stays nonzero.
Only the green column has a one in both inputs. AND clears the unread bit from the result and leaves the stored flags intact.
Keep the flag names beside the code that packs and reads them. Keep plain booleans where they make the rest of the code easier to read.
Bitwise operators on JavaScript Number values use 32 bits. Wider sets need another representation, such as BigInt for larger whole numbers or several words in a typed array. Rollup used BigInt flags for sets of dependencies, and Parcel moved its large flag sets to typed arrays.
Evidence
Node made the state object for readable streams about 40 percent smaller by storing its booleans as bits in one number.
Why keep each numeric field in its own array?
The ideaGroup values by field so a loop reading one field can step through neighbouring numbers.
Walk through it
Three product rows each hold a price and a stock count. If you add the prices, a loop finds each row object and reads its price.
A typed array stores values of one numeric type side by side. Make one for prices and one for stock counts. The first slot of each array belongs to the first product.
In the diagram, green marks prices two, five and eight. With columns, the loop reads those prices in order from a single block of numbers.
At a hundred thousand products, the loop still reads a hundred thousand prices. The price column keeps consecutive reads close together, which can help when the processor fetches memory in blocks.
Green marks the prices being added. Row objects are reached through separate references. The typed price column holds all three values together.
The fix
Use one typed array per field, a layout called struct of arrays. A Float64Array can hold prices with fractions. A Uint32Array holds nonnegative whole numbers in a fixed range, which works for these stock counts.
Size both arrays from the input list and fill them using the same row positions. Then a loop that adds prices can read price alone.
// Before
const oldTotal = rows.reduce((sum, row) => sum + row.price, 0);
// After
const price = Float64Array.from(rows, (row) => row.price);
const stock = Uint32Array.from(rows, (row) => row.stock);
const newTotal = price.reduce((sum, value) => sum + value, 0);
Watch out
Choose a type that fits the data. For example, Uint32Array converts fractions and wraps numbers outside its range.
Keep row positions aligned across columns when you reorder them. Conversion takes work up front, so measure it too if you only scan once.
Evidence
A FOSDEM talk reported about 9 nanoseconds per sample for a profiler query after its numeric data moved into separate typed columns.
Remember
A bit flag gives one true or false field a named position in a number.
A mask selects that position so you can check it with AND.
Typed columns keep the values for one field side by side.
Words used in this lesson
Term
Plain meaning
Bit
A digit with value zero or one.
Bit flag
A bit that represents one yes or no answer.
Mask
A number that selects the bits you want to test or change.
Typed array
A block of consecutive values of the same numeric type.
Struct of arrays
A layout with one array for each field and a shared position for each row.
Quick check
What does the pinned mask return when the stored flags equal five?
AND returns zero because five turns on the starred and unread bits. The pinned mask only keeps the bit worth two, which is off.
Which values describe the second product in the column diagram?
Read the second slot from each column to get a price of five and a stock count of three. Both slots refer to the same row.
Would numeric columns always help if every read needs price and stock?
The loop would have to read both columns, so the benefit of reading only prices disappears. Measure the loop and the conversion cost together.
A request often waits for its lookups one at a time, even when most of them do not need each other. After this lesson you can start independent waits together and turn many small requests into one.
What you will learn
How to tell which awaits really depend on each other, and run the rest together with Promise.all.
Why one request for 100 items beats 100 requests, even when the 100 run at the same time.
Why do three 20 ms lookups take 60 ms?
The ideaIf a lookup does not need another lookup's result, start it straight away, so the waits overlap instead of adding up.
Walk through it
A page needs three things: the user, the user's cart and the user's permissions. Each one is a lookup in a database or another service, and each takes 20 milliseconds (ms). Nearly all of it is waiting, not computing.
A Promise is a value that stands for a result that will arrive later. Calling getUser() starts the lookup and hands you a Promise at once. Then await pauses your function until that Promise has its result.
In the top half of the diagram, each lookup starts only after the one above it has finished. So the waits add up: three times 20 ms is 60 ms. Yet only the permissions lookup needs something from another lookup, which is the user's role.
The cart needs only the cart id, and the request already has it. So the user and the cart can both start at time zero, which we call the first wave. Permissions start when the user arrives, in the second wave, so the page is ready at 40 ms.
Each box is one 20 ms wait on the shared time axis. The red line is when the serial version is done; the green line is when the two-wave version is done.
Now scale it up. The course demo needs nine 20 ms lookups, such as session, user, role and teams, so one after another they take 180 ms. Grouped by what they need, they form two waves. In the second diagram, each wave lasts as long as its longest chain: 40 ms, then 60 ms. So the total drops to 100 ms.
Each small box is one 20 ms lookup, and lookups in one row depend on each other. Rows in the same wave run side by side, so a wave costs only its longest row.
The fix
Call every independent function first, then wait for them together. Promise.all takes a list of Promises, waits until all of them have results, and returns the results in the same order as the list.
// Before: each lookup waits for the one above it
const user = await getUser(userId);
const cart = await getCart(cartId);
const perms = await getPermissions(user.roleId);
// After: wave 1 starts both lookups before waiting
const [user, cart] = await Promise.all([getUser(userId), getCart(cartId)]);
// Wave 2 needs the role from wave 1
const perms = await getPermissions(user.roleId);
Watch out
Promise.all fails as soon as one lookup fails, but the other lookups keep running. Use Promise.allSettled when you need every outcome, for example to clean up.
A wave waits for its slowest lookup. When chains differ a lot, wrap each chain in its own async function and run the chains together, as the demo does.
Evidence
No source in this course measured this pattern. In the course demo on one machine, nine lookups took about 180 ms in a row and about 100 ms in two waves.
Why is one request for 100 items faster than 100 requests?
The ideaAsk once with all the keys instead of once per item, so you pay for one round trip, not one per key.
Walk through it
A page lists 10 orders and shows each customer's name. A common first version loads the orders with one query. Then, for each order, it loads that order's customer with its own query, which makes 11 queries.
Each query is a round trip: the request travels to the database, the database works, and the answer travels back while your code waits. Say one round trip takes 5 ms. Eleven in a row cost 55 ms, as the top row of the diagram shows.
This shape is called N+1: one query for the list plus one per row. The bottom row sends all 10 customer ids in one query, so it needs two round trips, about 10 ms. With 1,000 orders, N+1 makes 1,001 round trips, about 5 seconds.
O is the orders query and C is a customer query; each box is one 5 ms round trip. The red boxes are the extra round trips that batching removes.
Why not start the 10 customer queries together with Promise.all? That overlaps the waits, but the database still gets 10 requests, and it parses, plans and answers each one separately.
Requests also share a small connection pool, a fixed set of open database connections. In the diagram below the pool has 4, so 10 requests need three rounds while the batch needs one.
Illustrative. Each row of red boxes is one connection; requests 5 to 10 wait for a free one. The batch sends one request with all 10 ids.
The fix
Collect the keys, send one query for all of them, and match the answers back by key. In SQL that is WHERE id IN (...), and for an HTTP service it is a batch endpoint.
// Before: one query per order (N+1)
for (const order of orders) {
const [customer] = await db.query('SELECT * FROM customers WHERE id = ?', [order.customerId]);
order.customer = customer;
}
// After: one query for all ids, then match the rows by key
const ids = [...new Set(orders.map((o) => o.customerId))];
const rows = await db.query('SELECT * FROM customers WHERE id IN (?)', [ids]);
const byId = new Map(rows.map((c) => [c.id, c]));
for (const order of orders) order.customer = byId.get(order.customerId);
When lookups are spread across many functions, such as GraphQL resolvers, a loader like DataLoader collects the keys for you. It gathers every key asked for in one turn of the event loop (lesson 11), then sends one batched request.
Watch out
A batch can return rows in any order and leaves out keys it did not find. Match results to inputs by key, as the Map in the code does.
Very long key lists can hit query or URL size limits, so split them into chunks of a few hundred (a rule of thumb).
Evidence
No source in this course measured it, so count your own queries per request. An N+1 shows up as a count that grows with the number of rows.
Try it
Run the demo (2 minutes)
Run node demos/serial-vs-parallel.js from the course folder and read Part 1. On one machine, nine lookups in a row took about 181 ms and two waves took about 101 ms. Two waves with cached permissions took about 81 ms. The cached row shows one more trick: a lookup you skip costs nothing. Part 2 belongs to the next lesson.
Remember
Awaits in a row add their waits together, so keep the order only where one step needs another step's result.
Start independent lookups together in waves with Promise.all. The slowest lookup sets each wave's time.
When a loop sends one request per item, send one request with all the keys and match the results by key.
Words used in this lesson
Term
Plain meaning
Promise
A value that stands for a result that arrives later.
await
Pauses the current function until a Promise has its result.
Promise.all
Waits for a list of Promises and returns all results in input order.
Round trip
A request going to a server and its answer coming back.
N+1
One query for a list, plus one more query for every row in it.
Connection pool
A fixed set of open database connections that requests share.
Quick check
A product page needs the product, its reviews and its seller. The URL has the product id, and the seller id is inside the product. What goes in the first wave?
The product and the reviews, because both need only the product id from the URL. The seller lookup needs product.sellerId, so it has to wait for the product and goes in the second wave.
const a = getA(); const b = getB(); const x = await a; const y = await b; Do the two lookups overlap?
Yes. Calling a function starts its work, and await only waits for the result, so both lookups are running before the first await. The catch: if b fails while you wait for a, Node may call it an unhandled rejection. Promise.all is the safer way to write it.
You replaced 100 awaited lookups in a loop with Promise.all over the same 100 lookups. Why might one batched query still be better?
Promise.all overlaps the waits, but the database still receives 100 requests and pays the fixed cost of each one. The requests also compete for a small pool of connections. One query with all 100 keys pays that cost once.
Some costs are tiny but get paid on every step: each await, each write call and each new process. After this lesson you can spot a fixed cost that repeats in a hot path and pay it once.
What you will learn
What the event loop does at each await, and why awaiting a value that is already there still costs time.
Why joining small writes into bigger ones makes a stream faster.
Why a few long-lived helper processes beat starting a new process per request.
What happens each time code reaches await?
The ideaEach await is one pass through the microtask queue, even when the value is already there, so keep work on ready values in plain functions.
Walk through it
JavaScript runs your code on one thread. The call stack holds the functions that are running right now. The event loop is the part that picks what runs next once the call stack is empty.
When a function reaches await, it stops and leaves the call stack, and the rest of it is parked. Once the awaited value is ready, a resume job goes into the microtask queue, which is a list of short follow-up jobs.
The event loop always empties the microtask queue before it takes anything from the task queue. That second queue holds timers and finished I/O, such as a network reply. So a resume runs soon, but never in the middle of other code.
Follow the numbers. The loop runs every microtask (2) before it takes even one task (3), so a resume never waits behind a timer.
Now add 4 ready numbers with sum += await x. Each number makes one pass: pause, queue the resume, empty the stack, resume, add. A plain loop does the 4 additions in one run, as the next diagram shows.
Illustrative widths. Each red block is one pass through the microtask queue; the blue blocks are the real work, which is the same in both rows.
With 1,000,000 numbers there are 1,000,000 passes. In the course demo on one machine, the plain loop took about 12 ms. The await version took about 101 ms, roughly 8 times slower.
The fix
Await only the things that really wait, such as a network call. Keep helpers that work on ready values synchronous, which means they return their answer directly instead of a Promise.
// Before: async wraps plain arithmetic in a Promise, one queue pass per row
async function formatTotal(n) { return n.toFixed(2); }
for (const order of orders) totals.push(await formatTotal(order.total));
// After: a plain function returns the string directly
function formatTotal(n) { return n.toFixed(2); }
for (const order of orders) totals.push(formatTotal(order.total));
Libraries take this further. Vue's server renderer now returns a plain string when every part is ready, and returns a Promise only when it meets a real one.
Watch out
A function that returns either a value or a Promise is harder to call correctly. Do this only in code that runs thousands of times per request.
Awaiting a ready value does not let a timer or click in, because the microtask queue empties first. In the yield demo, chunks that only awaited still made a click wait about 280 ms.
Evidence
In Vue's server renderer, skipping Promises for ready values raised a mixed benchmark from about 0.3 million to 3.3 million operations per second.
Why are many small writes slower than one big one?
The ideaEvery write call has a fixed cost, so join ready pieces and write them together, just before you have to wait for something.
Walk through it
A server sends a large CSV file through a stream, which delivers a response in pieces as they become ready. The simple version calls res.write() once per row. Each call does the same bookkeeping: it checks the stream's state, turns the text into bytes and adds them to a queue.
In the diagram, each red block is that fixed cost and each blue block is one row's data. Six writes pay the fixed cost six times. One joined write sends the same six rows and pays it once.
Illustrative widths. The blue data is the same in both rows; only the number of red fixed costs changes.
With 5,000 rows, writing per row makes 5,000 calls, while flushing every 1,000 rows makes 5. One template engine in the sources produced 87 small chunks per page, and each chunk went through its own Promise and its own stream write.
The fix
Collect rows in an array and write the joined string when the array is full, before any real wait, and at the end. Also respect back-pressure: when res.write() returns false, the stream's buffer is full, so wait for its 'drain' event before writing more. The once helper comes from node:events.
// Before: one write call per row
for (const row of rows) res.write(toCsvLine(row));
// After: one write call per 1,000 rows
let buf = [];
for (const row of rows) {
buf.push(toCsvLine(row));
if (buf.length === 1000) {
if (!res.write(buf.join(''))) await once(res, 'drain'); // buffer full: wait
buf = [];
}
}
res.end(buf.join('')); // the last rows, then close
Watch out
Bigger chunks mean the first bytes arrive later. Flush what you already have before any slow wait, so the reader can start.
The buffer holds memory until it is written, so keep it bounded. A thousand rows is a starting point, not a rule.
Evidence
In one streaming template engine, joining strings and flushing them only before a real wait raised throughput from about 940 to 1,550 requests per second.
Why does starting a process per request hurt?
The ideaStarting a process has a large fixed cost, so start a few helper processes once and send each job to a free one.
Walk through it
Some servers run a command-line tool for each request, for example to convert a file. A process is a running program with its own memory. To spawn one, the operating system creates it, loads the program and connects its input and output.
In Node, part of spawn() runs on the main thread and blocks it. In the top row of the diagram, three requests each spawn the tool. So the main thread is stuck three times and serves nothing else meanwhile.
In the bottom rows, the server starts two helper processes once, when it boots. For each request it only sends a short message, and a helper does the spawning. So the main thread stays free, and both helpers can work at the same time.
Red blocks are time the main thread cannot serve anything. In the pool, the main thread only sends short messages (blue ticks), and the helpers do the spawning side by side.
At scale this matters: one server that spawned per request spent about 30% of its time with the main thread blocked inside spawn(). If the helper can do the work itself, for example by loading a library once, it skips the spawn completely.
The fix
Start the helpers with fork() from node:child_process when the server starts. The code is a sketch: pickFreeHelper is your own small function, and each helper replies with a message that carries the same job id.
// Before: every request spawns the tool on the main thread
const child = spawn('convert-tool', [input, output]);
await once(child, 'close');
// After: fork two helpers once, when the server starts
const helpers = [fork('helper.js'), fork('helper.js')];
// Per request: hand the job to a free helper, which spawns the tool
pickFreeHelper(helpers).send({ id, args: [input, output] });
Watch out
Each idle helper holds memory. Keep the pool small and limit how many jobs may wait for a free helper.
Handle helpers that crash and give each job a timeout, so every caller gets a result or an error. In the same benchmark, worker threads were slower than plain spawning, so measure before choosing.
Evidence
In one Node benchmark that ran a tiny command per request, a pool of forked helpers raised throughput from about 650 to 2,200 requests per second.
Try it
Run the demos (3 minutes)
Run node demos/serial-vs-parallel.js from the course folder and read Part 2. On one machine, adding 1,000,000 ready numbers took about 12 ms in a plain loop and about 101 ms with an await per number.
Then run node demos/yield.js and find the line for chunks with await only. The click still waits about 280 ms, because microtasks do not let it in. The setTimeout(0) line lets it in after about 1 ms.
Remember
Each await is one pass through the microtask queue, so await only what really waits.
Join ready output into bigger writes, flush before real waits, and respect back-pressure.
Start costly helpers once and reuse them, instead of paying the start-up cost on every request.
Words used in this lesson
Term
Plain meaning
Event loop
The part of the runtime that picks the next job once the call stack is empty.
Microtask queue
Short follow-up jobs, such as resuming after an await. All of them run before the next task.
Task queue
Bigger jobs such as timers and finished I/O. The loop takes one at a time.
Back-pressure
A stream's signal that its buffer is full, so the writer should pause.
Spawn
Start a new process: create it, load the program and connect its input and output.
Helper pool
A few long-lived helper processes that take jobs one after another.
Quick check
async function double(n) { return n * 2; } is awaited for each of 10,000 numbers. What does that cost, and what is the fix?
Every call returns a Promise, and every await on it is one pass through the microtask queue. So the loop makes 10,000 passes for plain arithmetic. Drop async and call double directly, which gives the same answer with nothing queued.
A loop awaits Promise.resolve() between chunks of work to let other code run. Does a waiting timer get a turn?
No. The resume goes into the microtask queue, and the event loop empties that queue before it takes a timer from the task queue. To really let other work in, end the chunk with a task such as setTimeout or setImmediate.
Why not keep a whole 50 MB file in memory and write it once?
One write has the lowest fixed cost, but the whole file sits in memory and the reader receives nothing until the end. Bounded chunks keep most of the saving, keep memory small and get bytes flowing early.
Read more
How Vue's server renderer stopped creating Promises for ready values. vuejs/core #11340
The same idea in Astro, including a side effect on streaming to watch for. withastro/astro #13195
Every object your code creates has to be cleaned up later, and a loop that creates millions of throwaway objects makes that clean-up run again and again. After this lesson you can spot per-row garbage and rewrite a busy loop so it creates almost nothing.
What you will learn
How V8 splits memory into a young and an old generation, and what a scavenge does.
Why the number of objects a loop creates decides how often your code pauses.
How to rewrite common per-row patterns so they create nothing new.
Where do new objects go, and who cleans them up?
The idea
New objects land in a small young area that a quick clean-up empties often, and your code pauses each time it runs.
Walk through it
Every object, array, string or function you create is stored in the heap, the memory where JavaScript values live. Storing a new value there is called an allocation. You never free memory yourself, because the garbage collector (GC) does it: it finds values nothing uses any more and reuses their space.
V8, the engine inside Chrome and Node, splits the heap in two, because most objects die young. New objects go into a small young generation. When it is full, V8 runs a quick clean-up called a scavenge.
Picture a young generation with room for 10 objects, as in the first diagram. When it fills up, 8 of the 10 are already garbage, shown in red. The scavenge copies only the 2 green survivors into a fresh, empty half, then treats the full half as empty. So its cost depends on how many objects survive, not on how much garbage there is.
An object that survives two scavenges is moved, or promoted, to the large old generation. A slower full collection cleans that area, but much less often.
Illustrative: real young generations hold many thousands of objects. Only the 2 green objects are copied; the 8 red ones cost nothing to drop.
A scavenge is fast, but your JavaScript stops while it runs. The second diagram shows why the number of allocations matters. Each new object fills the young generation a little more. So a loop that allocates five times as fast reaches "full", and pauses, five times as often.
Illustrative. The blue line is how full the young area is. Each time it touches the dashed line, a red scavenge pauses the code.
The fix
You cannot switch the collector off, so the fix is to give it less to do. First, check whether it matters: count the collections while your code runs. Node reports each one as a performance entry, and node --trace-gc prints a line per collection.
// Count garbage collections while your loop runs (Node)
const { PerformanceObserver } = require('node:perf_hooks');
let gcs = 0;
new PerformanceObserver((list) => { gcs += list.getEntries().length; })
.observe({ entryTypes: ['gc'] });
runTheLoop();
setImmediate(() => console.log('collections:', gcs)); // entries arrive a moment later
Watch out
Each throwaway object is cheap. Only worry when a profile shows time in garbage collection, or scavenges run hundreds of times during one task.
Objects you keep, such as a big array of rows, survive and get promoted, so every full collection must walk them. Lesson 14 covers that.
Evidence
In OpenTelemetry, a tracing library, one function was rewritten to allocate less. Its memory per call fell from about 1 kB to 0.4 kB, and it ran about a quarter faster.
Which everyday code creates garbage on every row?
The idea
Object.entries, spreads, chained array methods and functions written inside a loop all build throwaway objects, and a hot loop multiplies them.
Walk through it
A hot loop is code that runs once per row, per request or per item. Anything it creates is multiplied by the number of times it runs.
Take one order row with 8 number fields, and add them up. Object.entries(row) first builds an outer array, then one small [key, value] array per field. In the third diagram, that is 9 red arrays for one row, and the loop reads each one once and drops it. A for...in loop reads the fields in place, so it creates nothing.
Now scale it up. 100,000 rows read 20 times makes 2 million row visits, and 9 arrays per visit makes 18 million throwaway arrays. The young generation fills again and again, so scavenges keep interrupting the loop.
Each red box is one array that lives for a moment and then becomes garbage. Multiply by 100,000 rows and 20 passes.
The same pattern hides in other places. { ...row, label } copies every field into a new object. .map().filter() builds a new array at each step. An arrow function written inside the loop is a new function object on every pass. The Bluebird promise library got much of its speed by creating such helper functions once, at the top level, instead of on every call.
The fix
Pick a way to loop that builds nothing new, and create helpers once outside the loop. Object.hasOwn skips keys inherited from the prototype, which Object.entries never showed you either.
// Before: 1 outer array + 8 pair arrays for every row
for (const [key, value] of Object.entries(row)) sum += value;
// After: reads the fields in place, creates nothing new
for (const key in row) {
if (Object.hasOwn(row, key)) sum += row[key]; // skip inherited keys
}
// Copy only the fields you need, not { ...row, label }
const out = { id: row.id, status: row.status, label };
Watch out
Only rewrite loops that run per row or per request and show up in a profile. A loop that runs once at start-up is fine either way.
An explicit field list breaks quietly when someone adds a field to the source object, which the spread version would have copied.
Evidence
In OpenTelemetry, swapping Object.entries for for...in made setting 10 attributes on a span, the timing record created for each request, about 22% faster.
Try it
Try it (2 minutes)
Run node demos/entries-vs-forin.js from the course folder. It sums 100,000 rows of 8 fields 20 times, both ways, and counts garbage collections. Check that it prints same result: true, then compare the two lines, as in the chart below. Add --trace-gc after node to see every scavenge printed as it happens.
One machine, Node 22. Each panel has its own scale. Half the time, and about 14 times fewer collections, for the same answer.
Remember
New objects go into a small young generation; a scavenge copies the survivors and pauses your code while it runs.
The more a loop allocates, the more often it pauses, so in hot loops avoid Object.entries, spreads, chained array methods and per-row functions.
Measure first: rewrite only loops that run per row or per request and show up in a profile.
Words used in this lesson
Term
Plain meaning
Heap, allocation
The memory where JavaScript values live; an allocation is storing a new value there.
Garbage collector (GC)
The part of the engine that finds values nothing uses any more and reuses their memory.
Young and old generation
The small area where new objects start, and the large area for objects that lived longer.
Scavenge
The quick clean-up of the young generation: copy the survivors, treat the rest as empty.
Promotion
Moving an object that survived two scavenges into the old generation.
Hot loop
Code that runs once per row, request or item, so anything it creates is multiplied.
Quick check
A loop uses Object.entries over 12 settings once, when the server starts. Should you rewrite it?
No. It creates 13 small arrays once, which is far too little to measure. The rewrite only pays off when the loop runs per row or per request. Then the garbage is multiplied by thousands or millions and keeps triggering scavenges.
Why does a scavenge get slower when more objects survive, but not when there is more garbage?
A scavenge copies only the objects still in use and then treats the whole full half as empty. Garbage is never touched, so it costs nothing to drop. Survivors must each be copied, so they set the price.
A profile shows a lot of garbage collection time during a per-row loop. What do you look for first?
Look for things the loop body creates on every pass. Common ones are Object.entries, { ...row } copies, .map() or .filter() chains, and arrow functions written inside the loop. Each one is multiplied by the number of rows, so removing them cuts how often the young generation fills.
JavaScript frees memory for you, yet a server or a browser tab can still grow until it crashes. After this lesson you can trace what keeps an object alive and cut the one link that should not be there.
What you will learn
What the garbage collector can free, using roots and reachability.
How a cache, a closure or a promise chain keeps big objects alive.
How to find the culprit by comparing two heap snapshots.
If JavaScript has a garbage collector, how can it leak?
The idea
The collector frees only what nothing can reach, so a leak is an object that something long-lived still points to.
Walk through it
A full collection starts from a few roots: module-level and global variables, the functions running right now, and active timers and event listeners. It follows every reference from those roots and marks each object it reaches. A marked object is reachable and stays; everything else is freed.
Take a server with a module-level cache Map that stores each report it builds, keyed by request id. Three requests come in. In the first diagram, the two old requests, in the dashed box at the bottom left, are freed, because no root points to them any more. The three reports stay, because a path leads to each one: module scope, then cache, then the report.
Arrows mean "holds a reference to". The old requests have no path from a root, so they are freed. Cut the red links and the reports are freed too.
Nothing ever deletes from the cache, so every request adds a report that can never be freed. Say each report is 50 KB, a made-up round number: 10,000 requests make 500 MB. That is a memory leak, memory your program still points to but will never use again.
The second diagram shows how a leak looks from outside. Healthy memory rises and falls around a flat floor. With a leak, the floor left after each collection keeps climbing.
Illustrative. Each drop is a garbage collection. Watch the dashed floor: flat is fine, climbing means something keeps a path to old objects.
The fix
Give every long-lived collection a way to let go: a size limit, an expiry time, or a delete when the work is done. A Map remembers the order of inserts, so its first key is always the oldest.
// Before: grows forever, reachable from module scope
const cache = new Map();
function remember(key, value) { cache.set(key, value); }
// After: keep at most 1,000 entries; drop the oldest
function remember(key, value) {
cache.set(key, value);
if (cache.size > 1000) cache.delete(cache.keys().next().value);
}
Watch out
A leak needs something long-lived, such as a module variable, a global listener or a timer. Short-lived local variables are freed normally.
An event listener added on every request or render and never removed is the same leak, with the event source as the root.
Evidence
In three.js, model names kept a reference into the whole model file, so one app reached about 1 GB after about 10 view changes. Lesson 15 shows why.
How can a tiny function keep a big object alive?
The idea
Functions created in the same scope share one record of its variables, so a function you cache can keep a big neighbour alive.
Walk through it
A closure is a function plus the variables around it that it can use. In V8, when any function in a scope uses a variable, that variable goes into one shared context record for the scope. Every function created there points to that same record.
Take a React component that decodes a 10 MB preview for a download button and also calls React Query, a data-fetching library. onDownload uses preview, and queryFn only uses id. Both still point to the same record, as the Before panel of the third diagram shows.
React Query keeps queryFn in its cache so it can fetch again later. The cache holds queryFn, which holds the record, which holds the preview. As the user clicks, old records and their previews pile up, so memory climbs on every click.
Follow the arrows from the cache. The shared record keeps the 10 MB preview alive. The hook record holds only the id, so the preview can be freed.
The fix
Move useQuery into a small custom hook. The hook is its own function, so queryFn gets its own record that holds only id.
// Leak: queryFn shares the component's record, which holds preview
const preview = decode(payload);
const onDownload = () => save(preview);
const { data } = useQuery({ queryKey: ['user', id], queryFn: () => fetchUser(id) });
// Fix: the hook's record holds only id
function useUser(id) {
return useQuery({ queryKey: ['user', id], queryFn: () => fetchUser(id) });
}
Watch out
Reading the id from queryKey inside queryFn did not help in the write-up; only a separate function did.
This is engine behaviour, not a React Query bug, and it only matters when something long-lived, such as a cache, holds the function.
Evidence
In the write-up's demo, heap snapshots showed the 10 MB object kept alive 8 times before the fix, and flat memory after it.
Why can a retry written with .then() leak?
The idea
A promise that waits on another keeps it alive, so a retry that chains to itself grows by one link per failure.
Walk through it
A retry helper sends some data. If the send fails, it waits 100 ms and calls itself, and it returns that new attempt from inside .then(). So the first promise can only settle when the second one does, and the second only when the third does.
In the fourth diagram, each failed try adds one box to the chain. None of them can be freed, because the first promise is still waiting for the last. If the destination is down for an hour, 10 tries per second make 36,000 links for one message. Many messages retrying at once multiply that again.
Each try in the red chain waits on the next one. The promises can be freed once the whole chain settles. The loop holds one try at a time, so finished tries can be collected.
The fix
Write the retry as a loop with await. The function keeps one pending try at a time, and each finished try has nothing pointing to it, so it becomes garbage.
// Before: every failure adds a link to one growing chain
function sendWithRetry(d, dest) {
return dest.send(d).catch(() => delayMs(100).then(() => sendWithRetry(d, dest)));
}
// After: one loop, one pending try at a time
async function sendWithRetry(d, dest) {
for (;;) { try { await dest.send(d); return; } catch { await delayMs(100); } }
}
Watch out
Add a maximum number of tries. Also wait a little longer after each failure, called backoff, so a dead service cannot keep work queued forever.
Short outages are harmless. The chain only becomes a problem during long or endless retries.
Evidence
In one 2019 write-up, thousands of streams retried this way during an outage. The process ran out of memory and crashed; the post gives no memory figures.
Try it
Try it in your own app (5 minutes)
Open Chrome DevTools on your page, or run Node with node --inspect app.js and open chrome://inspect. In the Memory tab, take a heap snapshot, which is a picture of every object in memory. Repeat the action you suspect 5 times, then take a second snapshot. Switch the view to Comparison and sort by # Delta. Objects whose count grew by about 5 are your suspects. Click one and read its Retainers panel, which lists the path from a root that keeps it alive.
Remember
An object lives as long as any path leads to it from a root, so a leak is an unwanted path from something long-lived.
Caches need a limit, and functions you hand to a cache should come from a small scope, such as a custom hook.
Retry with a loop and await, not a .then() chain that calls itself.
Words used in this lesson
Term
Plain meaning
Root
A starting point the collector always keeps: globals, module variables, running functions, timers and listeners.
Reachable
An object some chain of references leads to from a root. Reachable objects are never freed.
Memory leak
Memory the program still points to but will never use again.
Closure, context
A function plus the variables around it; V8 keeps those variables in one record shared by every function from that scope.
Heap snapshot
A picture of every object in memory, with what holds each one.
Backoff
Waiting a little longer after each failed retry.
Quick check
Server memory climbs on every request and never falls back, even after collections. What do you look for?
Look for something long-lived that gains an entry per request: a module-level cache, a listener that is added but never removed, or a timer. Compare two heap snapshots, then read the Retainers path of the objects whose count grows. That path ends at the root you need to cut.
Why does moving useQuery into a custom hook fix the leak?
Functions from one scope share one record of its variables. Inside the component, that record also holds the big preview, because another function uses it. The hook is its own scope, so its queryFn gets a record that holds only the id.
A recursive .then() retry runs during a 10-second outage. Is that a problem?
Not really. At 10 tries per second it builds about 100 links, and they are all freed once a try succeeds and the chain settles. It becomes a leak only when the outage is long or endless, so the chain keeps growing.
A big job crashes with "heap out of memory" because of how much it holds at the same moment, not because of how much data it handles in total. After this lesson you can shrink each row to what the code reads, and stream big data so the peak stays small.
What you will learn
Why every field you load but never read costs memory and time.
What peak memory and the live set are, and why streaming keeps them small.
How back-pressure stops a fast reader from flooding a slow writer.
Why load fields nobody reads?
The idea
Every field you load is sent, decoded, stored and later cleaned up, so ask only for the fields your code reads.
Walk through it
A list screen shows three columns: number, status and total. Each order row in the database has about 40 columns, and the code runs SELECT *, which asks for all of them.
For each row, the database sends 40 values and the program builds 40 values in memory. An ORM is a library that turns rows into objects with methods such as save(). Many ORMs wrap each row in a model object that tracks changes. Building that rich object is called hydration.
In the first diagram, the screen reads only the 3 green cells of each row, and the 37 red cells are built for nothing. With 1,000 rows, that is 40,000 values plus 1,000 model objects to show 3,000 values. At 100,000 rows the waste runs into millions of objects.
Each square is one value built in memory for one row. Three rows shown; a real list repeats this for every row it loads.
The fix
Name the fields you need. That list is a projection: the database sends only those fields, and your code builds only those. If you only read the rows, also ask your ORM for plain objects instead of models. Most have an option for this, often called raw or lean.
// Before: 40 columns per row, often wrapped in model objects
const rows = await db.query('SELECT * FROM orders WHERE status = $1', ['open']);
// After: only the 3 columns the screen shows
const rows = await db.query(
'SELECT id, status, total FROM orders WHERE status = $1', ['open']);
Watch out
Plain, partial objects are for reading. Saving a partly loaded record through an ORM can overwrite fields it never loaded.
When the screen gains a column, add the field to the query too, or the new column stays empty.
Evidence
A log-processing service called split('\t') on every line, which built every field though only two were used. The fix moved the parser into a native Rust add-on that copies only what it keeps. Memory on one test file fell from about 381 MB to under 2 MB, as the second diagram shows.
One test file, from the write-up, on a shared scale. The fix was a native parser, not streaming JavaScript; the lesson for you is to build only the fields you use.
Why hold every row when you only need one at a time?
The idea
Peak memory is what you hold at the same moment, so stream big data a batch at a time and write each result as you go.
Walk through it
An export writes 400,000 rows to a CSV file, and each row takes about 2 KB as a JavaScript object. That is a made-up round number to keep the arithmetic easy. A first version loads every row into one array, turns each into a line, and joins the lines into one big string.
While that array exists, all 400,000 rows sit in memory at once: about 800 MB, plus the string. The objects in use at one moment are called the live set, and peak memory is the largest it ever gets. In the third diagram, the red line climbs with every row read.
A stream, or a database cursor, hands you rows a batch at a time instead. With batches of 1,000 rows, the live set stays near 2 MB however many rows there are. The green line rises and falls with each batch but never grows.
Illustrative, assuming about 2 KB per row and batches of 1,000. The red line ends where the job may crash. The green line stays near the baseline, with the changes between batches exaggerated so they’re visible.
The fix
Read with your database library's stream or cursor, write each line, and let the row go. One trap remains: if the file or network is slower than the database, written lines pile up in the output's buffer instead. Back-pressure is the output's signal that its buffer is full: write() returns false, so you wait for the 'drain' event before writing more. The fourth diagram shows the pause.
const { once } = require('node:events');
// Before: every row in memory, then one huge string
const rows = await db.query('SELECT id, status, total FROM orders');
out.write(rows.map(toCsvLine).join('\n'));
// After: one batch at a time; pause while the output is full
for await (const row of db.stream('SELECT id, status, total FROM orders')) {
if (!out.write(toCsvLine(row) + '\n')) await once(out, 'drain');
}
Here db.stream stands for whatever your library calls its stream or cursor.
Illustrative. The blue line is how full the output buffer is. When it reaches the red "full" line, the reader stops until the 'drain' event, so memory never grows past one buffer.
Watch out
pipeline() from node:stream connects a source to an output, handles back-pressure for you, and cleans up both ends if a step fails.
A cursor keeps a database resource open. If your loop can stop early or throw, close it in a finally block when your library needs that.
Evidence
None of this course's sources measured an export like this, so treat it as a rule of thumb. With streaming, peak memory is about batch size times row size, not total rows times row size.
Try it
Try it on your own export (5 minutes)
Run it with a small heap limit: node --max-old-space-size=256 export.js. On a large enough input, a load-everything version fails with "JavaScript heap out of memory", while a streaming version finishes. Log process.memoryUsage().heapUsed every 10,000 rows to watch the line stay flat.
Remember
Load only what you read: a projection, plus plain objects when you only read.
Peak memory is what you hold at once, so stream big data a batch at a time.
Respect back-pressure: when write() returns false, wait for 'drain', or let pipeline() do it.
Words used in this lesson
Term
Plain meaning
Projection
The list of fields you ask a query for, so the rest are never sent or built.
ORM, hydration
A library that turns rows into objects with methods; hydration is building those rich objects.
Live set
All the objects in use at one moment.
Peak memory
The largest the live set ever gets. Memory near the limit is what crashes a process.
Stream, cursor
Ways to read data a piece or a batch at a time instead of all at once.
Back-pressure
An output's signal that its buffer is full, so the writer should wait.
Quick check
An endpoint loads 20 fields per item and the screen shows 4. Does a projection help even if memory looks fine?
Yes. The database sends less, the server decodes and stores less, and the garbage collector has less to clean up. The response is smaller too, so every step of the request gets cheaper, not just memory.
An export holds 400,000 rows in one array and peaks at about 3 GB. What do you change first, and why does it help?
Stream it with a cursor and write each row as it arrives, with a projection so each row is small. Peak memory is set by how many rows are held at once. With a stream that is one batch, so the peak no longer grows with the number of rows.
A streaming export still grows in memory when the network is slow. Why?
The code probably ignores back-pressure: it keeps calling write() after it returned false. The lines then pile up in the output's buffer instead of in an array. Wait for 'drain', or use pipeline(), so the reader pauses while the buffer is full.
Read more
My Node.js is a bit Rusty: per-line garbage, out-of-memory runs, and a native Rust parser as the fix.
Strings and parsing · Lesson 15 of 28 · about 10 minutes
Strings: slices and scanning
A short piece of text can keep a whole file in memory, and a simple search can read farther than you need. You’ll learn when to copy a slice and how to stop a search as soon as you have the answer.
What you will learn
You’ll see how a short string can keep its source in memory.
You’ll choose between checking the start of a string and finding the first separator.
Why can a short name keep a whole file in memory?
The idea
Keeping a string slice can keep its original text in memory when the two share storage.
Walk through it
Suppose you save Amber Notebook from the first line of an upload in a cache, which holds values for later use. Your cache stores the result of slice, which takes a range between two positions in a string.
V8, the engine that runs JavaScript in Node.js and Chrome, can represent that slice by recording a start, a length, and a reference. A reference is a link to data, so the slice can read its letters from the original text.
Now scale the upload to 40 megabytes while keeping the same name. In the top row of the diagram, the cache holds the slice and the slice still points into the upload. Clearing the upload variable leaves that second link in place.
The garbage collector frees data that your running program can no longer reach. It must keep the whole source string while the cached slice depends on any part of it.
Follow the red link from the slice to the upload. The green copy holds the same name in its own storage, so the upload can be freed.
The fix
When a long-lived cache holds a slice, try rebuilding just the small field. JSON.stringify writes the name as quoted text and escapes special characters, and JSON.parse reads it back into the original string value. The lower row shows the separate storage this produced in one Node.js example.
// Before
cache.set(id, upload.slice(start, end));
// After
const name = upload.slice(start, end);
cache.set(id, JSON.parse(JSON.stringify(name)));
Watch out
Check a memory snapshot, which records what is held in memory, for a link from the cached field to the source. Verify the change with the engine version you deploy, because the language gives no guarantee about string storage.
Sharing storage saves copying when the source and slice are both used briefly.
Evidence
In one three.js memory report, object names retained the text of a roughly 40 megabyte model file.
How far does a string search need to go?
The idea
Find the first separator when you need a position, and check only the beginning when you need a prefix.
Walk through it
Take note:ready:today and keep the key before the first colon. The colon is a separator, a character that divides the fields. Calling split(':') finds both colons and builds an array of three pieces before your code keeps the first.
In the first scan diagram, indexOf(':') can stop at the first colon. On a line with thousands of later separators, it can still stop at the same place. That avoids making an array and extracting the fields your code would discard.
The dots line up with the colons. The red span is work past the boundary you need, and the green scan ends at that boundary.
A prefix is the start of a string. If you only want to know whether item.user.saved starts with user., the first character gives you the answer. The second scan diagram shows where the two calls can stop.
The red scan looks for a match anywhere. The green dot shows where a prefix check can reject the string, even if the string is much longer.
The fix
Use the position of the first colon to take the key in one slice. For a prefix, startsWith only needs to compare the leading characters, so a long suffix adds no further search.
indexOf returns -1 when the colon is missing, so return the whole line to match split(':')[0].
Use split when you want all the fields. When everything after the first colon is one value, slice after it to keep any later colons intact.
Evidence
A Fastify search could scan roughly 16 kilobytes of header text before it was replaced with a prefix comparison.
Remember
Follow a cached string’s references when a large source stays in memory.
Use indexOf to find the first separator when all you need is a boundary.
Use startsWith when only the beginning matters.
Words used in this lesson
Term
Plain meaning
Slice
A piece of a string between two positions.
Reference
A link to data stored elsewhere.
Garbage collector
The part of the engine that reclaims memory for unreachable data.
Separator
A character that divides fields.
Prefix
The start of a string.
Quick check
Why might clearing the upload variable leave the file in memory?
The cache can still hold a slice that reads its letters from the upload. The garbage collector can release the original text once nothing still refers to it.
How would you read note:ready:today as a key and one value?
Find the first colon with indexOf, then slice on each side. The value stays ready:today because its colon is past the boundary you used.
Strings and parsing · Lesson 16 of 28 · about 10 minutes
Regex and parsing
A regular expression, or regex, describes a text pattern, and some patterns retry the same text many ways before giving up. You’ll learn to spot retries, write more precise patterns, and read a simple format one character at a time.
What you will learn
You’ll trace why repeats inside repeats can make a failed match expensive.
You’ll see when checking ahead makes a pattern read the same characters twice.
You’ll follow a small scanner that keeps its place as it reads.
Why can a failed match take so long?
The idea
When two repeats can divide the same text in many ways, a failed match can make the engine retry those divisions.
Walk through it
Suppose a label needs lowercase letters followed by a colon. In /^(?:[a-z]+)+:$/, ^ and $ mark the start and end. [a-z] matches one lowercase letter in that range, and + means one or more of the thing before it.
The inner repeat takes a run of letters. (?:...) groups it, so the outer + asks for one or more runs.
Try abc, with the colon missing. The engine can first take abc as one run and fail to find a colon. It can then shorten that run to ab and use a second run for c.
This retry still fails. Going back to try a different match is called backtracking. The diagram shows four ways to use all the letters.
Each blue box is one run. On the second row, the engine gives the last letter its own run, but the red mark shows the same failure.
There are two possible breaks between three letters, and each break can be present or absent. Each extra letter adds another break and doubles the choices. With twenty letters, there are more than half a million possible full divisions. An engine may skip some paths.
The fix
One run is enough to describe the label. With one +, the engine may still shorten the run after a failure, but it has no reason to divide it into more runs.
// Before
const nested = /^(?:[a-z]+)+:$/;
// After
const single = /^[a-z]+:$/;
Watch out
Include failed matches when you measure a pattern, because a valid input may match on the first path.
Remove a repeat only when it describes the same accepted strings. A separator between runs can make the grouping part of the format.
Evidence
In a separate Java settings parser benchmark, reading characters directly was at least four times as fast as trying several regexes per line.
When does looking ahead repeat work?
The idea
A lookahead can read text without advancing the match, so the next part of the pattern may read the same text again.
Walk through it
Now check a label and a number, like tag:7. A lookahead is a check that leaves the match position where it started. In a regex, (?=...) checks that its contents match from the current position.
Suppose (?=[a-z]+:) first checks for letters and a colon. It reads tag: and succeeds, but the next part still starts at the t. The diagram highlights the same span being read twice.
On a long label, the second pass rereads the whole label. A lookahead that checks one character can be much cheaper.
The red arc leads back to the start of tag:. The green line shows one match that reads the prefix and number together.
The fix
Match the letters and colon once, then read one or more digits with [0-9]+. Matching the prefix already proves it is present.
// Before
const checkTwice = /^(?=[a-z]+:)[a-z]+:[0-9]+$/;
// After
const checkOnce = /^[a-z]+:[0-9]+$/;
Watch out
A lookahead may enforce a rule the rest of the pattern misses. Check that both versions accept and reject the same cases before changing it.
Evidence
In a separate valibot email benchmark, a revised pattern without lookaheads did about 50 percent more matches per unit of time.
When can a scanner read the format directly?
The idea
A scanner uses the current character and position to decide what to read next.
Walk through it
Parsing turns text into parts your program can use. Suppose you want a lowercase key and any text after the first colon. In tag:7:ok, that gives you the key tag and the value 7:ok.
A scanner uses a cursor, which is a number that tracks its place. The cursor advances one step for each letter and stops at the colon. The diagram shows how that position determines both slices.
Across thousands of rows, the loop reads only the key on each row. Each colon ends that row’s scan of the key, so more colons in the value create no new choices.
The blue arrows stop at the first colon. The green brackets mark the two slices, so the second colon stays in the value.
The fix
Advance while the key has lowercase letters. Require at least one letter and a colon, then slice the two fields. The regex below returns the same fields, with s allowing its dot to read line breaks in the value.
// Before
const fields = line => /^([a-z]+):(.*)$/s.exec(line)?.slice(1) ?? null;
// After
function scan(line) {
let i = 0;
while (line[i] >= 'a' && line[i] <= 'z') i++;
if (i === 0 || line[i] !== ':') return null;
return [line.slice(0, i), line.slice(i + 1)];
}
Watch out
A scanner owns every rule in the format. Check empty fields and any special rules for quotes or escaped separators.
Keep the regex if it is clear and fast enough. Measure on your inputs before taking on a scanner.
Evidence
In a Less experiment, a scanner that skipped copying each piece of syntax ran about 20 times as fast as the global regex version.
Remember
Check how many ways repeated groups can divide the same text.
Check how far a lookahead reads before the main pattern starts.
Try a cursor when a simple format spends too much time in several pattern checks.
Words used in this lesson
Term
Plain meaning
Regex
A pattern for matching text.
Backtracking
Going back to an earlier choice to try a different match.
Lookahead
A check that reads ahead while leaving the match position in place.
Parsing
Turning text into parts the program can use.
Scanner
Code that walks through text to find its parts.
Cursor
The current position in the text.
Quick check
Why can the nested repeat retry after reading all of abc?
The missing colon makes the match fail, but the engine still has other ways to divide the letters into runs. A single repeat removes those choices about where to divide them.
Where does the main match start after the lookahead sees tag:?
It starts at the t. The lookahead confirms that text is present and leaves the starting position unchanged.
Why does the scanner keep the second colon in tag:7:ok?
Its cursor finds the end of the key at the first colon. The value is everything after that position, so it includes the second colon.
Rendering and CSS · Lesson 17 of 28 · about 10 minutes
One frame, and layout thrashing
A page stutters when the browser cannot finish a frame in time, and reading a size at the wrong moment is a common cause. After this lesson you can spot those reads and reorder your code so layout runs once per frame.
What you will learn
The five steps the browser runs to draw one frame, and which ones share a thread with your code.
Why reading a size right after a change forces extra layout, and how a loop turns that into layout thrashing.
How requestAnimationFrame turns many events into one update per frame.
What does the browser do to draw one frame?
The ideaThe browser saves up your changes and lays out the page once per frame, unless your code asks for a size in the middle.
Walk through it
A screen that refreshes 60 times a second gives the browser about 16.7 milliseconds to make each picture. One picture is called a frame.
To turn a change into pixels, the browser runs the steps in the first diagram. Style works out which CSS rules apply to each element. Layout works out the size and position of every element. Paint records how to fill in the pixels, and composite stacks the painted pieces into the final picture.
Illustrative, not to scale. Everything above the amber line must fit in one frame. The blue steps share one thread, so nothing else on it runs meanwhile.
The browser is lazy on purpose. When your code changes a class or a size, the browser only marks the layout as out of date. It plans to redo it once, at the end. But if your code then reads a size, such as offsetHeight, the browser cannot answer from stale data. It must run style and layout right now, which is called a forced synchronous layout, or forced reflow.
Take a link that shows a preview card on hover. The handler removes the link's title (a write), reads the link's position (a read), then inserts the card (more writes). In the second diagram, the read lands after a write, so layout runs early. The card insert then dirties it again, so layout runs twice in this frame.
Red is layout the browser ran only because a read came after a write. Moving the read first removes it.
The fix
Read sizes at the start of the handler, before you change anything. The page is still up to date from the last frame, so the read is cheap. Your writes then only mark layout as stale, and the browser redoes it once.
// Before: change, then measure, so layout runs early and again later
link.removeAttribute('title'); // write
const rects = link.getClientRects(); // read: forced layout
showPreview(link, rects); // more writes
// After: measure first, while the page is still clean
const rects = link.getClientRects(); // read: cheap
link.removeAttribute('title');
showPreview(link, rects);
Watch out
Reads that can force layout include offsetWidth, offsetHeight, clientWidth, scrollTop, getBoundingClientRect() and getComputedStyle().
A read with no pending write is cheap. Avoid reads that come straight after writes, not reads in general.
Evidence
One tooltip library changed the page and then read a position. That forced the browser to restyle 807 elements on the spot, about 67 milliseconds per hover.
Why does a loop of reads and writes get so slow?
The ideaAlternating reads and writes in a loop forces one layout per item, so do all the reads first and all the writes after.
Walk through it
Say 4 product cards should be square. For each card, the code reads its width and then sets its height to match. The first read is cheap, because nothing has changed yet. Each later read comes right after a write, so the browser must lay out the page again before it can answer.
In the third diagram, each red block is one of those forced layouts. With 4 cards there are 3, and the normal layout still runs at the end. With 500 cards there are 499 forced layouts in one frame. Repeated forced layout like this is called layout thrashing.
Each layout can cover the whole page, so its cost grows with page size as well as card count. That is why the same loop can feel fine on a small test page and freeze a large one.
Illustrative. Each red L is a full layout the browser ran early; the grouped version keeps only the green one.
The fix
Split the loop in two. The reads all happen while the page is clean, so none of them forces layout. The writes only mark layout as stale, and the browser lays out once, at the normal time.
// Before: read, write, read, write... one forced layout per card
cards.forEach((card) => {
const width = card.offsetWidth; // read after the last write: forced
card.style.height = `${width}px`; // write
});
// After: all reads first, then all writes, so layout runs once
const widths = cards.map((card) => card.offsetWidth);
cards.forEach((card, i) => { card.style.height = `${widths[i]}px`; });
Watch out
Thrashing often hides across functions: a helper that writes, then another helper that reads. Look at the order of calls, not just one loop.
Libraries can do it too. A tooltip or chart library that measures after inserting will force layout on every use.
Evidence
In one profile, four pointer-move events each changed and measured the page within one frame. That frame took about 546 milliseconds instead of 16.
What if events fire faster than frames?
The ideaLet fast events only record the latest value, and apply it once per frame inside requestAnimationFrame.
Walk through it
Events such as pointermove and scroll can fire several times within one frame. Say a user drags a slider handle, and 4 pointer events arrive before the next frame. If each event moves the handle and measures it, the page does 4 updates and 4 layouts. The screen only shows the last one.
requestAnimationFrame (often shortened to rAF) runs a callback just before the browser's next style and layout. In the last diagram, each event only stores itself as the newest value. One callback waits for the frame and reads that newest value, so 4 events become 1 update.
Grey ticks are the cheap "remember this event" step. The green callback reads only the newest event, e4.
The fix
Keep one flag that says a callback is already waiting. Every event overwrites the latest value, and only the first event in a frame schedules the callback. This works because the callback runs once per frame, whatever the event rate.
// Before: el.addEventListener('pointermove', (e) => moveHandle(e.clientX));
let latest = null;
let waiting = false;
el.addEventListener('pointermove', (e) => {
latest = e; // cheap: just remember it
if (waiting) return; // a callback is already scheduled
waiting = true;
requestAnimationFrame(() => { waiting = false; moveHandle(latest.clientX); });
});
Watch out
Modern browsers already line up most pointer events with frames, so measure before adding this everywhere. Window resize is still better handled with a debounce.
Inside the callback, keep reads before writes too. rAF limits how often you update, but it does not reorder your code.
Evidence
At 120 Hz a frame has only about 8 milliseconds, so one extra layout per event can use up the whole budget.
Try it
Try it (3 minutes)
Open any page with a long list in Chrome. In DevTools, open the Performance panel, start recording, scroll or drag for two seconds, then stop. Look for purple Layout blocks marked with a small red corner. Click one: the summary says "Forced reflow" and links to the line of JavaScript that read the size.
Remember
A frame has about 16.7 milliseconds at 60 Hz, and your JavaScript shares a thread with style, layout and paint.
Reading a size after a change forces layout now. In a loop, that becomes one layout per item.
Read first, write after, and apply fast events once per frame with requestAnimationFrame.
Words used in this lesson
Term
Plain meaning
Frame
One picture on the screen. At 60 per second, each has about 16.7 milliseconds.
Style, layout, paint, composite
The steps from a change to pixels: which rules apply, where things go, fill pixels, stack the pieces.
Forced synchronous layout
Layout that runs immediately because code read a size after changing the page.
Layout thrashing
Forcing layout again and again by alternating writes and reads, often in a loop.
requestAnimationFrame
Runs a callback once, just before the browser draws the next frame.
Quick check
A loop sets each card's height, then reads the next card's width. Why is it slow?
Each height change marks layout as out of date. The next width read cannot use stale numbers, so the browser lays out the page right then. Read all widths first, then set all heights, and layout runs once.
Is it bad to read offsetWidth at all?
No. A read is cheap when nothing has changed since the last layout, because the browser already has the answer. It only costs extra when it comes straight after a write in the same frame.
A drag handler runs 4 times per frame. What does requestAnimationFrame change?
The handler now only stores the newest event and schedules at most one callback. That callback runs once before the next frame, so 4 updates and layouts become 1. The user still sees the newest position, because that is the value the callback uses.
Rendering and CSS · Lesson 18 of 28 · about 10 minutes
Keep style changes small
One tiny change can make the browser recheck every element on the page, or build hundreds of extra layers. After this lesson you can keep each change on the smallest part of the page that needs it.
What you will learn
How far a style change spreads, and why an inherited CSS variable on a parent spreads it everywhere.
Why adding an element straight to <body> can restyle the whole page.
What layers are, and how too many or too big layers slow every frame.
How far does one style change spread?
The ideaThe browser rechecks every element a change could affect, so put fast-changing values on the one element that uses them, not on a parent of everything.
Walk through it
After a change, the style step marks which elements might now look different. This is called style invalidation. A class on one cell can only affect that cell and what is inside it. A CSS variable is inherited, which means every element inside can read it. So changing it on a parent makes the browser recheck all of them.
Picture a small grid: one root, 3 rows and 6 cells, so 10 elements. A scroll handler stores the scroll offset as a variable on the root, and only the rows layer uses it. In the top tree of the diagram, each scroll step marks all 10 elements red. In the bottom tree, the value is set on one row, so at most that row and its 2 cells are rechecked.
Now scale it up. A data grid with 1,000 cells rechecks 1,000 elements on every scroll step, many times a second.
Red circles are elements the browser rechecks after the change. The green box is the only part of the tree the change can reach.
The fix
Set fast-changing values directly on the element that uses them. If a value must stay a CSS variable, register it with @property and inherits: false, so changing it never spreads to children.
// Before: a variable every cell inherits, changed on every scroll step
grid.style.setProperty('--offset-top', `${top}px`);
// After: change only the element that moves
rowsLayer.style.transform = `translateY(${top}px)`;
/* If it must be a variable: stop it passing down to children */
@property --offset-top { syntax: "<length>"; inherits: false; initial-value: 0px; }
Watch out
A variable on the root is fine for values that rarely change, such as a theme or a compact-mode switch.
Moving a value into a new object prop can break React.memo on that component, as lesson 20 explains. One grid needed a second fix for exactly this.
Evidence
In a browser benchmark on a 1,000-element tree, a non-inherited registered variable was about 850 times cheaper to change than an inherited one.
Why can adding one element restyle the whole page?
The ideaAdd pop-ups such as tooltips to a small container that is always in the page, so the browser only rechecks that container.
Walk through it
A page has 800 elements. On hover, a tooltip library appends a tooltip straight to <body>, then reads a position to place it. The new element is a child of the element that holds everything, so the browser treats the whole page as possibly changed.
The read then forces the style step to run right away, as lesson 17 showed. In the top tree of the diagram, all 807 elements are rechecked on every hover. In the bottom tree, the tooltip goes into an always-present container, so only 3 elements are rechecked: the container, the tooltip and its text.
Red is rechecked on every hover. In the bottom tree, the change stays inside the small container branch.
The fix
Put one empty container at the end of <body> when the page loads, and render every tooltip and popover into it. Most UI libraries take a container option, and React portals take a target element.
// Before: each tooltip is added straight to <body>
document.body.appendChild(tip);
// After: one small container that is always in the page
// <div id="l18-tooltips"></div> at the end of <body>
document.getElementById('l18-tooltips').appendChild(tip);
Watch out
The root cause was a read after a write, so fixing that order (lesson 17) helps too. The container keeps the damage small when you cannot change the library.
This was measured on an older library version. Newer ones may behave differently, so check the Recalculate Style entry yourself.
Evidence
Moving tooltips into their own container cut style recalculation from about 67 milliseconds to under 1, because 3 elements were rechecked instead of 807.
Why do layers cost time and memory?
The ideaEvery layer is a separate picture the browser must manage each frame, so keep layers few and small.
Walk through it
Some elements get their own layer: a separately painted picture that the composite step can move without repainting. Elements with a transform or will-change often get one. Deciding and building layers shows up in DevTools as Layerize.
Take a grid where every cell is moved into place with its own transform. With 15 columns and 20 visible rows, that can mean 300 layers to sort out on each scroll step. In the top half of the third diagram, every cell is its own sheet. In the bottom half, one empty spacer at the start of each row pushes the cells into place, so they share one layer.
Illustrative. Red sheets each float on their own layer. Dashed boxes are the spacers; the cells after them simply flow.
Size matters as well as count. A common way to hide screen-reader text was to push it to left: -10000px. When it sat above a layered element, the browser could stretch a layer all the way out to cover it, as the last diagram shows.
The red dashed box is the layer the browser had to build. The 1 px box keeps the hidden text where it is, so the layer stays small.
The fix
Move a whole row once instead of every cell, and hide text with a tiny clipped box instead of a huge offset. Both keep the number and size of layers down.
// Before: every cell gets its own transform
<div className="cell" style={{ transform: `translateX(${x}px)` }} />
// After: one empty spacer per row, cells flow after it
<div className="cell-offset" style={{ width: offsetLeft }} />
// Before: hidden far off screen
{ position: 'absolute', left: '-10000px' }
// After: a 1 px clipped box that stays in place
{ position: 'absolute', width: 1, height: 1, overflow: 'hidden', clip: 'rect(0, 0, 0, 0)' }
Watch out
Each layer also uses GPU memory, so will-change on many elements can make things worse. Add it to the few elements that really animate.
Use the Layers panel in DevTools to see how many layers exist and how big they are before you change anything.
Evidence
Removing per-cell transforms in one data grid saved about 100 milliseconds of rendering for every 1,000 milliseconds spent, about a tenth.
Try it
Try it (3 minutes)
In Chrome DevTools, record a Performance profile while you hover tooltips or scroll a big table. Click a purple Recalculate Style block. The summary shows "Elements affected". If that is close to the whole page for a small change, look for a root variable or an element added to <body>.
Remember
A change on a parent can reach every element inside it, so put fast-changing values on the element that uses them.
Add tooltips and popovers to a small, always-present container, not straight to <body>.
Layers are not free: keep them few, keep them small, and check the Layers panel.
Words used in this lesson
Term
Plain meaning
Style invalidation
The browser marking elements that might look different after a change, so it can recheck them.
Inherited
A value that children read from their parent, such as a CSS variable or color.
@property
Registers a CSS variable with a type, and lets you say it should not pass down to children.
Recalculate Style
The DevTools entry for the style step, with a count of elements affected.
Layer, Layerize
A separately painted picture the browser can move cheaply; Layerize is the step that builds them.
Quick check
A drag handler updates a CSS variable on the app's root on every mouse move. Why does the page stutter?
The variable is inherited, so each change makes the browser recheck every element in the app, many times a second. Set the value on the element being dragged, for example as a transform. If it must stay a variable, register it with inherits: false.
Hovering a button shows a tooltip, and Recalculate Style says 800 elements affected. What do you try first?
Check where the tooltip is inserted. If it goes straight into <body>, the browser may recheck the whole page. Render it into a small container that is always present, then check the count again.
Why can adding will-change: transform to every row slow a page down?
Each row may get its own layer, and every layer must be built, tracked and stored in GPU memory. With hundreds of rows, managing layers costs more than it saves. Promote only the few elements that actually animate.
More to explore
Complex selectors can slow the style step on big pages. One gallery of 5,000 elements cut style time from over 900 ms to about 300 ms by simplifying a few.
Read more
MUI X #12019: stop changing CSS variables on the grid root while scrolling.
Rendering and CSS · Lesson 19 of 28 · about 10 minutes
Do not render what nobody sees
A long list can feel heavy even though the screen shows only 20 rows, because every row in the page costs work and memory. After this lesson you can choose between lighter rows, content-visibility and virtualisation.
What you will learn
Why the number of elements in the page matters, even for rows nobody can see.
How virtualisation keeps only the visible rows in the page.
How content-visibility: auto lets the browser skip off-screen sections, and when to pick which.
Why is a long list heavy when only 20 rows show?
The ideaEvery element in the page costs style, layout and memory, whether or not it is on screen, so count elements and make each row lighter.
Walk through it
The DOM is the tree of elements the browser keeps for the page. Say an order history shows 2,000 orders, and each row is about 10 elements: a few cells, a badge and a button. That is 20,000 elements, but the screen shows only about 20 rows, which is 200 elements.
Style and layout work grows with the number of elements, as lessons 17 and 18 showed. So the 19,800 elements off screen still slow every restyle, and each one holds memory. In the diagram, the red bar is what the page holds and the tiny green bar is what anyone can see.
Same scale for both bars. Only 1 element in 100 is visible, yet all of them take part in every restyle.
The fix
First, make each row lighter. Remove wrapper elements nobody needs, and replace an icon image inside a button with a background on the button itself. Fewer elements per row means less work on every row, on or off screen.
<!-- Before: two elements per item, and every image loads -->
<button><img src="party.png" alt="party"></button>
<!-- After: one element; the image is a background, set when on screen -->
<button class="emoji" aria-label="party" style="--img: url(party.png)"></button>
/* CSS: .onscreen .emoji { background-image: var(--img); } */
Watch out
Lighthouse, the page audit built into Chrome, warns above about 800 elements and reports an error above about 1,400. Treat these as rough signals, not hard limits.
One listener per row multiplies the same way. One listener on the list, which catches clicks bubbling up from rows, is cheaper.
Evidence
An emoji picker halved its elements from about 40,000 to 20,000 this way, and its benchmark went from about 224 milliseconds to about 144.
How does virtualisation keep a list small?
The ideaVirtualisation keeps only the rows near the screen in the page and swaps them as you scroll, so the page size stays the same for 2,000 or 200,000 rows.
Walk through it
Say each row is 30 pixels tall and the list box is 600 pixels tall, so 20 rows fit. The full list would be 2,000 times 30, which is 60,000 pixels. An empty spacer of that height keeps the scrollbar the right size.
When the user scrolls to 15,000 pixels, the code divides by 30 and gets row 500. It renders rows 495 to 524: the 20 on screen plus 5 extra above and below, called the buffer. In the diagram, only the solid rows exist. Everything else is empty space.
Illustrative. Only the solid rows exist in the page, 30 out of 2,000. The dashed outline is just height.
The fix
Work out the first and last row from the scroll position, render that slice, and move it down to where it belongs. Libraries such as react-window and TanStack Virtual do this for you, including rows of different heights.
// Before: render(rows) puts all 2,000 rows in the page
const ROW = 30, VIEW = 600, BUFFER = 5;
const first = Math.max(0, Math.floor(scrollTop / ROW) - BUFFER);
const last = Math.min(rows.length, first + VIEW / ROW + 2 * BUFFER);
spacer.style.height = `${rows.length * ROW}px`; // right scrollbar
slice.style.transform = `translateY(${first * ROW}px)`; // move into place
render(rows.slice(first, last)); // about 30 rows
Watch out
Rows that do not exist cannot be found with Ctrl+F or printed. One code viewer laid a transparent text area holding the full text over the visible lines to keep Ctrl+F working.
Very fast scrolling can show blank space before new rows arrive. A bigger buffer in the direction of scrolling helps.
Evidence
One code viewer measured about 0.9 milliseconds per line, so a 52,000-line file would take about 47 seconds. Virtualised, it renders only the visible lines.
Can the browser skip off-screen work for you?
The ideacontent-visibility: auto keeps every element in the page but lets the browser skip style, layout and paint for sections that are off screen.
Walk through it
Group the 2,000 orders into 50 day sections of 40 rows each. Give each section content-visibility: auto. The browser now lays out and paints only the sections near the screen. The others stay in the page, so Ctrl+F and screen readers still find them.
A skipped section has no measured height, so the scrollbar would jump. contain-intrinsic-size gives it a guessed height to use until it comes on screen. In the diagram, the grey sections are skipped placeholders and only the middle one is drawn in full.
Grey sections still exist, so find and screen readers work. The browser just does not draw them until they come near the screen.
The fix
Add two CSS lines to each section. The auto keyword in contain-intrinsic-size tells the browser to remember the real height once it has seen the section.
/* Before: every day section is styled, laid out and painted */
.day { }
/* After: skip the work for sections that are off screen */
.day {
content-visibility: auto;
contain-intrinsic-size: auto 1200px; /* 40 rows of 30 px, guessed while skipped */
}
The last diagram compares all three options on the same list. Use content-visibility when sections have predictable heights and you want find to keep working. Use virtualisation when the list is very long, such as tens of thousands of rows.
Blue frames are the screen. Red rows are rendered for nobody, grey rows are in the page but skipped, and dashed rows do not exist at all.
Watch out
content-visibility is slower than virtualisation for very large lists, because every element still exists. Older Safari versions do not support it.
A guessed height that is far off makes the scrollbar jump as sections come into view. Base the guess on rows times row height.
Evidence
Adding content-visibility to each emoji category made the picker's benchmark about 15 percent faster in Chrome, from about 270 milliseconds to about 227.
Try it
Try it (2 minutes)
Open a long list page in your app, open the DevTools console and run document.querySelectorAll('*').length. Scroll to the bottom and run it again. If the count is in the thousands and grows as you scroll, the list is a candidate for lighter rows, content-visibility or virtualisation.
Remember
Every element costs style, layout and memory, on screen or not, so count them and make rows lighter.
Virtualisation keeps only the visible rows plus a buffer, which scales to very long lists but breaks find and print.
content-visibility: auto keeps all elements but skips drawing off-screen sections; give them a guessed height.
Words used in this lesson
Term
Plain meaning
DOM
The tree of elements the browser keeps for the page.
Virtualisation
Keeping only the rows near the screen in the page and swapping them as you scroll.
Buffer
A few extra rows rendered just outside the screen, so scrolling does not show gaps.
content-visibility: auto
CSS that lets the browser skip style, layout and paint for a section while it is off screen.
contain-intrinsic-size
The guessed size a skipped section uses, so the scrollbar stays steady.
Quick check
Only 20 rows are visible. Why do the other 1,980 rows still slow the page down?
They are still elements in the page, so every restyle and layout includes them, and each one holds memory. Being off screen does not remove them from the browser's work. Make rows lighter, skip them with content-visibility, or virtualise the list.
Users need Ctrl+F to find text anywhere in a long page of sections. Which technique fits?
content-visibility: auto, because every element stays in the page, so find and screen readers still see it. Virtualisation removes off-screen rows entirely, so find cannot reach them without a workaround.
A virtualised list shows blank gaps when scrolled fast. What helps?
A bigger buffer, especially in the direction the user is scrolling. The buffer rows are already rendered before they come on screen, so there is less to fill in at the last moment.
Rendering and CSS · Lesson 20 of 28 · about 10 minutes
React re-renders
Ticking one checkbox in a long list can make React redo every row, because a parent update re-renders its children by default. After this lesson you can make unchanged rows skip, and keep per-row setup from multiplying.
What you will learn
Why one state change re-renders a whole list, and how memo lets unchanged rows skip.
Why memo often does nothing, and how to give it props that stay the same.
Why per-row listeners and store subscriptions add up, and how to do them once.
Why does one checkbox re-render the whole list?
The ideaWhen a component's state changes, React re-renders it and every child below it, unless a child is wrapped in memo and its props did not change.
Walk through it
A re-render means React calls a component function again and compares the result with last time. Take an order list with 5 cards. The list keeps the selected ids in its state, as a Set, and passes that set to every card.
Tick the checkbox on card 2. The list's state changes, so the list renders again, and so do all 5 cards. Only card 2 looks different, but React still called all 5 functions. In the top tree of the diagram, every red box is a card that rendered for nothing but card 2.
With 1,000 rows, one click means 1,000 component calls, plus the comparison work for each.
Blue is where the state changed. Red cards rendered again; green cards were skipped because their props were the same.
The fix
Wrap the card in memo, which skips a render when every prop is the same as last time. Then pass each card only what it needs: a selected true or false, not the whole set. Ticking makes a new set, which would count as a changed prop for every card, but the boolean only changes for card 2.
// Before: every card gets the whole set, which is new on every tick
function OrderCard({ order, selectedIds }) { /* ... */ }
<OrderCard order={order} selectedIds={selectedIds} />
// After: memo, and a boolean that only changes for the ticked card
const OrderCard = memo(function OrderCard({ order, selected }) { /* ... */ });
<OrderCard order={order} selected={selectedIds.has(order.id)} />
Watch out
memo is not free, because it compares props on every render. Use it on components that render often with mostly unchanged props, such as list rows.
A re-render is not a page update. React only touches the page for what changed, but the function calls and comparisons still cost time.
Evidence
After a spreadsheet app removed needless re-renders and repeated work around each cell edit, it did about a quarter of the JavaScript work per edit.
Why does memo sometimes do nothing?
The ideamemo checks whether each prop is the very same value as last time, so a function or object created during render makes it re-render every time.
Walk through it
memo does a shallow compare. It checks each prop with Object.is, which asks "is this the very same value or object?", not "does it look the same?". This sameness of objects is called identity.
Follow card 3 after card 2 is ticked, in the diagram. order is the same object as last time. selected was false and is still false. But onSelect is an arrow function written inside the list, so each list render makes a new function. A new function is never the same object as the old one, even with identical code, so card 3 renders anyway.
Each row is one Object.is check. A single red "new" is enough to make the card render.
The fix
Give memo props that keep their identity between renders. useCallback returns the same function until one of its dependencies changes, and useMemo does the same for a computed object or array. A constant object can move out of the component, so it is made only once.
// Before: a new function and a new object every render, so memo never skips
<OrderCard order={order} style={{ margin: 8 }} onSelect={(id) => setSelected((s) => toggle(s, id))} />
// After: the same references every render, so unchanged cards are skipped
const cardStyle = { margin: 8 }; // outside the component
const onSelect = useCallback((id) => setSelected((s) => toggle(s, id)), []);
<OrderCard order={order} style={cardStyle} onSelect={onSelect} />
Watch out
A useCallback with a missing dependency keeps an old copy of the function that reads stale state. The updater form, setSelected((s) => ...), avoids needing that state as a dependency.
Arrays built in render, such as items.filter(...), are new every time too. Wrap them in useMemo if a memo child receives them.
Evidence
In one spreadsheet app, a grid library rebuilt an array on every render, so memo never matched and a single cell edit caused 1,568 re-renders.
Why does per-row setup add up so fast?
The ideaSetup that every row repeats, such as adding the same global listener or reading the same store many times, multiplies by the row count, so do it once.
Walk through it
A dropdown has 100 items. When each item mounts, it adds the same two listeners, for keydown and mousedown, to the document. Opening the dropdown makes 200 addEventListener calls. The browser ignores the duplicates, but it still pays for every call.
In the diagram, 4 items make 8 calls at the top. At the bottom, the first item installs the listeners and the other 3 see a flag and skip. Store reads multiply the same way. If each of 1,000 items reads shared state through 10 separate useSyncExternalStore calls, that is 10,000 hook calls per render. One library merged them into one call per item and its large lists rendered 20 to 30 percent faster.
Each line is one addEventListener call. Red lines are repeats the browser throws away after paying for them.
The fix
Keep a module-level flag, so the listeners are installed by the first item and skipped by the rest. For store reads, combine each item's reads into one subscription that returns everything the item needs.
// Before: every item ran the two addEventListener calls on mount
// After: the first item installs them, the rest skip
let installed = false; // shared by all items
function useFocusable() {
useEffect(() => {
if (installed) return; // every item after the first skips
installed = true;
document.addEventListener('mousedown', onGlobalMouseDown, true);
document.addEventListener('keydown', onGlobalKeyDown, true);
}, []);
}
Watch out
This only helps when many components add the very same listener. Listeners that differ per row are better replaced by one listener on the list that finds the row from the click.
For thousands of items, virtualisation (lesson 19) still wins, because rows that do not exist do no setup at all.
Evidence
Adding the global listeners once instead of per item made a dropdown open about 30 percent faster.
Try it
Try it (2 minutes)
Open a list page in your own React app with React DevTools installed. In the Components tab settings, turn on "Highlight updates when components render", then tick one row's checkbox. If every row flashes, look for a prop that is a new set, function or object on each render.
Remember
A state change re-renders that component and everything below it, unless memo sees unchanged props.
memo compares by identity, so a new function, object or array made in render defeats it.
Per-row setup multiplies by the row count: install shared listeners once and merge store reads.
Words used in this lesson
Term
Plain meaning
Re-render
React calling a component function again and comparing its result with last time.
memo
Wraps a component so it skips rendering when all its props are the same as last time.
Shallow compare, identity
Checking each prop with Object.is: is it the very same value or object, without looking inside.
useCallback, useMemo
Hooks that return the same function or value until a dependency changes.
useSyncExternalStore
The React hook a component uses to read and subscribe to a store outside React.
Quick check
An OrderCard is wrapped in memo but still renders every time the list does. What do you check first?
Check whether any prop is created during the parent's render, such as an inline arrow function, {}, [] or a new Set. memo compares by identity, so a new object counts as changed even when its contents match. Use useCallback, useMemo, or move constants outside the component.
Why pass selected={selectedIds.has(order.id)} instead of the whole set?
Ticking a box creates a new set, so every card would see a changed prop. The boolean only changes for the card that was ticked. So memo can skip all the others.
A list of 500 items each calls the same store hook 5 times. What would you change?
Merge the 5 reads into one subscription per item that returns an object with all 5 values. That cuts 2,500 hook calls per render to 500. For lists in the thousands, also consider virtualisation.
An animation stutters when the browser cannot get the next picture ready before the screen refreshes. After this lesson you can pick properties that keep every frame cheap, and animate a list reorder without animating layout.
What you will learn
How much time one frame gets, and what the user sees when a frame is late.
Which CSS properties make the browser redo layout or paint, and which only move finished pixels.
How FLIP turns a reorder into one cheap transform per row.
How much time does one frame get?
The idea
At 60 refreshes per second, each new picture must be ready within 16.7 ms, or the screen shows the old picture again.
Walk through it
A screen redraws itself at a fixed rate, and each still picture it shows is called a frame. At 60 refreshes per second there are 1,000 divided by 60, about 16.7 ms, between refreshes. That gap is the frame budget. On a 120 Hz screen it shrinks to about 8 ms.
Take a drawer that slides open over 300 ms. At 60 Hz that is 18 frames, so the browser must build 18 pictures, each inside its own 16.7 ms slot. Your JavaScript, style, layout and paint (lesson 17) all share that one slot.
In the diagram, frames 1 and 3 take 10 ms and fit. Frame 2 takes 25 ms, so it is not ready at the 33.3 ms refresh. The screen shows frame 1 a second time, then frame 2 arrives late and the drawer jumps. Users feel that jump as a stutter, often called jank.
Dashed lines mark screen refreshes. Frames 1 and 3 take 10 ms each. Frame 2 misses the refresh at 33.3 ms, so the screen shows frame 1 again.
The fix
If JavaScript drives the motion, update once per frame with requestAnimationFrame, which calls your function just before the browser draws. A 10 ms timer fires once or twice per refresh, so some updates are never shown and the steps are uneven. Compute the position from elapsed time, so one late frame does not slow the whole animation.
// Before: a timer on its own clock, 3 px per tick
setInterval(() => { x += 3; box.style.transform = `translateX(${x}px)`; }, 10);
// After: once per frame, position from elapsed time
const start = performance.now();
function step(now) {
const t = Math.min((now - start) / 300, 1); // 0 to 1 over 300 ms
box.style.transform = `translateX(${t * 300}px)`;
if (t < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
Watch out
requestAnimationFrame only decides when your code runs. If the work inside takes 25 ms, the frame is still late.
A fast laptop hides missed frames. Test with CPU throttling in DevTools or on a slow phone.
Evidence
The Motion animation guide puts the budget at 16.7 ms per frame at 60 frames per second, and about 8 ms at 120.
Which properties are cheap to animate?
The idea
Animate transform and opacity, because the browser can reuse pixels it already drew instead of redoing layout and paint.
Walk through it
Each frame passes through stages. Style works out which CSS rules apply. Layout works out the size and position of every box. Paint turns boxes into pixels. Composite stacks finished pieces, called layers, into the final picture.
Animate the drawer's width from 0 to 420 px, and each of the 18 frames has a new width. Text rewraps and boxes move, so layout, paint and composite all run 18 times. Animate box-shadow, and the boxes stay put, but every frame needs new shadow pixels, so paint runs 18 times.
Animate transform or opacity on a drawer with its own layer, and the browser only moves or fades the stored picture. The grid shows which stages each property repeats.
Red rows redo style and paint, and width also triggers layout. Green only composites. This is typical when the element has its own layer, and browsers differ.
There is a second win. CSS transitions and animations of transform and opacity can run on the compositor, a separate thread that does not wait for your JavaScript. If a re-render blocks the main thread for 100 ms, a width animation loses about 6 frames, while a transform animation keeps moving.
Each dot is one 16.7 ms frame slot. Red rings mark missed frames. The compositor keeps showing new frames in green.
The fix
Give an overlay drawer its final width once, then slide it in from off screen with a transform.
A transform moves the picture but not the box's layout slot, so neighbours do not move aside. If they must, use FLIP (next section).
Styles set from requestAnimationFrame always run on the main thread, even for transform. Prefer a CSS transition or element.animate() for simple motion.
Evidence
The Motion guide notes that a re-render can easily take over 100 ms. That is about 6 lost frames for any animation that needs the main thread.
How do you animate a reorder without animating layout?
The idea
Apply the final layout at once, use a transform to draw each row at its old spot, then slide that offset to zero.
Walk through it
A list shows notes A, B and C, and each row is 32 px tall. The user pins C, so it jumps to the top. Animating top or margins would redo layout on every frame. FLIP avoids that in four steps: First, Last, Invert, Play.
First: read C's position before the change, which is 64 px from the top. Last: move C to the top in the DOM and read again, which gives 0. Invert: subtract first minus last, so 64 minus 0 is plus 64 px. Setting translateY(64px) draws C exactly where it was.
Rows A and B each moved down one slot, so their offsets are 0 minus 32, which is minus 32 px. Play: animate every offset to zero over 300 ms. In the diagram, small dashed boxes are layout slots and big boxes are what you see. Only step 4 runs on every frame.
Small dashed boxes are layout slots. Big boxes are where each row is drawn. The first three steps happen once after the click. Only Play runs every frame.
The fix
Read every row's position, reorder once, read again, and animate the signed difference to zero. The reads happen once, and the 300 ms of motion is pure transform.
// Before: the pinned row jumps to the top
list.prepend(pinned);
// After: FLIP every row
const rows = [...list.children];
const first = rows.map((r) => r.getBoundingClientRect().top); // First
list.prepend(pinned); // Last
rows.forEach((r, i) => {
const dy = first[i] - r.getBoundingClientRect().top; // Invert
if (dy) r.animate([{ transform: `translateY(${dy}px)` },
{ transform: 'none' }], { duration: 300 }); // Play
});
Watch out
Read all first positions before the change and all last positions after it. Mixing a read and a write per row forces layout again and again (lesson 17).
Scaling with FLIP can stretch text, and starting a new FLIP while one is still running needs care.
Evidence
The FLIP article fits the one-time measuring into the roughly 100 ms after a click, a delay users do not notice.
Try it (2 min)
In Chrome DevTools, open the Rendering panel and turn on Paint flashing. Animate a drawer's width, then the same drawer with a transform. Green flashes on every frame mean paint is running; the transform version should flash once or not at all.
Remember
One frame gets 16.7 ms at 60 Hz and about 8 ms at 120 Hz. A late frame shows up as a jump.
Animate transform and opacity. Animating width, top or box-shadow redoes layout or paint on every frame.
For a reorder, use FLIP: measure, move, invert with first minus last, then play the offset to zero.
Words used in this lesson
Term
Plain meaning
Frame budget
The time between two screen refreshes, which is all the time one new picture gets.
Layout
Working out the size and position of every box on the page.
Paint
Turning boxes, text and shadows into pixels.
Compositor
The part of the browser that stacks stored layers into the final picture, on its own thread.
requestAnimationFrame
A browser call that runs your function once, just before the next frame is drawn.
FLIP
First, Last, Invert, Play: apply the final layout, then animate a transform from the old spot to zero.
Quick check
At 60 Hz, frame 2 takes 25 ms. What does the user see?
Frame 2 is not ready at the 33.3 ms refresh, so the screen shows frame 1 a second time. Frame 2 then appears at 50 ms. The motion pauses and then jumps, which reads as a stutter.
Why can a transform animation keep moving while JavaScript is busy, but a width animation cannot?
A new width needs layout, and layout runs on the main thread, so every frame waits for your JavaScript to finish. A CSS transform animation only moves a stored layer, which the compositor can do on its own thread.
A row moves from top 0 to top 96. What does the Invert step apply?
First minus last is 0 minus 96, which is minus 96, so it applies translateY(-96px). That draws the row back at its old spot. Play then animates the offset to zero, so the row slides down.
More to explore
View transitions use the same idea. One post replaces their default width and height keyframes with a translate-only FLIP, so the motion runs on the compositor.
Shadows and blurs look simple, but animating them makes the browser draw new pixels on every frame. After this lesson you can fade a fixed effect instead, and estimate what the extra layers cost in memory.
What you will learn
Why animating a shadow or blur repaints every frame, and how fading a fixed copy avoids it.
How a cross-fade between pre-blurred copies works.
How to estimate layer memory, and why many cheap animations still cost CPU.
Why is animating a shadow slow?
The idea
Every new shadow size has to be painted from scratch, so paint one fixed shadow and fade it in with opacity.
Walk through it
A card lifts on hover: its shadow grows from nothing to a soft 24 px edge over 300 ms. At 60 Hz that is 18 frames (lesson 21). Each frame has a different shadow, so the browser must paint it again. Painting here means working out the soft edge and turning it into pixels, which is called rasterising.
Now paint the full shadow once, on a separate box behind the card, and change only that box's opacity. Opacity is applied when layers are stacked, so the stored shadow pixels are reused. In the diagram, each red cell is a paint and each green cell is a cheap blend. The top row paints 18 times; the bottom row paints once.
Each cell is one 16.7 ms frame. Red cells redraw the shadow; green cells reuse it.
The fix
Put the shadow on ::after, a box that CSS generates for you. Keep the shadow itself fixed and transition only its opacity.
/* Before: a new shadow is painted on every frame */
.card { transition: box-shadow 300ms; }
.card:hover { box-shadow: 0 8px 24px #0004; }
/* After: one fixed shadow, only its opacity changes */
.card { position: relative; }
.card::after { content: ""; position: absolute; inset: 0;
border-radius: inherit; pointer-events: none;
box-shadow: 0 8px 24px #0004; opacity: 0; transition: opacity 300ms; }
.card:hover::after { opacity: 1; }
Watch out
The ::after box may get its own layer while it fades, which costs memory (section 3).
The Motion guide lists filter: drop-shadow() as a swap for animating box-shadow. Check either choice with Paint flashing.
Evidence
None of the sources measured this exact case, so treat it as a rule of thumb. The Motion guide ranks box-shadow as paint-only: cheaper than layout, dearer than transform and opacity.
Why is a blur so expensive, and how do you fade one in?
The idea
A blur mixes every pixel with its neighbours, so blur a few fixed copies once and cross-fade between them with opacity.
Walk through it
To blur, each output pixel becomes an average of the pixels around it. The blur radius says how far around it looks. With a radius of 4 px, a simple blur reads a 9 by 9 square, which is 81 pixels, for every pixel. At 8 px it reads 17 by 17, which is 289. Real blurs take shortcuts, but the cost still grows with the radius and the area.
Illustrative, for a simple square blur. Doubling the radius makes each pixel mix about 3.6 times as many neighbours.
Now animate a backdrop's blur from 0 to 8 px over 300 ms. Every frame has a new radius, so every pixel of the backdrop is blurred again, 18 times. The cheaper way is a cross-fade, which blends one picture out while another comes in. Keep a sharp copy, a 2 px copy and an 8 px copy, each blurred once, and change only opacity. In the diagram, each pair of lines crosses at a 50/50 mix, so the blur seems to grow smoothly.
Only opacity changes, so no copy is blurred again. The circles mark the moments when two copies are mixed half and half.
The fix
Stack the copies, promote their shared wrapper to a layer, and transition opacity in turn. Each copy on top hides the one below as it fades in, which gives the crossing lines above.
This only works for content that does not change, because each copy is blurred once. For live content, a plain translucent tint may be enough.
Every copy is another full-size layer. Start with one blurred copy and add levels only if the fade looks wrong.
Evidence
In the blur article, four cross-faded copies held a steady 60 frames per second, even on a low-end phone.
What do layers and many small animations cost?
The idea
A layer costs about 4 bytes of memory per device pixel, and every running animation costs CPU on every frame, so keep both counts small.
Walk through it
A layer is a piece of the page stored as its own picture, so it can be moved or faded without painting again. That picture needs memory, often on the graphics card (GPU). A rough estimate is width times height in device pixels, times 4 bytes, one each for red, green, blue and transparency.
Device pixels are the screen's real dots. On a high-density screen with 2 device pixels per CSS pixel, a 300 by 200 card becomes 600 by 400. That is 240,000 pixels, or about 1 MB. A full-screen 1440 by 900 backdrop becomes 2880 by 1800, about 21 MB. The three blur copies from section 2 are about 62 MB.
Estimated pixel storage on a shared scale, at 2 device pixels per CSS pixel and 4 bytes per device pixel. Real layer memory varies by browser and device.
Animation count is a separate cost, paid in CPU instead of memory. Even a cheap opacity animation needs a new value on every frame. One spinner with 25 pulsing dots runs 25 animations, so 20 spinners run 500, as the grid shows.
Each square is one spinner. Each red dot is one running animation; each green ring is one image playing the whole effect.
The fix
Promote an element to a layer only while it moves, and replace many tiny animations with one pre-made animated image per spinner.
/* Before: a permanent layer on every card */
.card { will-change: transform; }
/* After: a layer only while it is dragged */
.card.dragging { will-change: transform; }
/* Before: 25 animations per spinner */
.spinner .dot { animation: pulse 1.2s infinite; }
/* After: one animated image, tinted with the text colour */
.spinner { mask-image: url(spinner.apng); background: currentColor; }
Watch out
Rotating one wrapper is cheaper still, but it changes the look: the dots spin together instead of pulsing in turn.
An animated image still has to be decoded as it plays, and it needs a build step. Respect reduced-motion settings in both versions.
Evidence
With 20 spinners on screen, switching to one animated image each cut total CPU use by about three quarters.
Try it (2 min)
In Chrome DevTools, open the Rendering panel and turn on Paint flashing. Hover a card whose shadow grows, then one that fades a fixed shadow: the first flashes green on every frame. Then open the Layers panel, pick a layer, and compare its memory estimate with width times height times 4.
Remember
Animating a shadow or blur repaints every frame. Paint the effect once and fade it with opacity.
For a blur, cross-fade a few pre-blurred copies, and only for content that does not change.
Layers cost about 4 bytes per device pixel, and animations cost CPU on every frame. Count both.
Words used in this lesson
Term
Plain meaning
Rasterise
Turn drawing instructions, such as a soft shadow edge, into actual pixels.
Blur radius
How far around each pixel a blur looks when it mixes neighbours.
Cross-fade
Blending one picture out while another fades in, using only opacity.
Layer
A piece of the page stored as its own picture, so it can move or fade without a new paint.
Device pixel
One real dot on the screen. High-density screens use several per CSS pixel.
will-change
A CSS hint that an element is about to animate, which often gives it its own layer.
Quick check
Why does fading a fixed shadow cost less than growing it?
A growing shadow has new pixels on every frame, so paint runs 18 times in 300 ms. A fixed shadow is painted once. Fading it only changes how strongly the stored pixels are blended, which happens when layers are stacked.
Estimate the memory of one full-screen 1440 by 900 layer on a screen with 2 device pixels per CSS pixel.
That is 2880 by 1800 device pixels, about 5.2 million. At 4 bytes each it is about 21 MB. Three such copies would be about 62 MB, which is why you start with one copy.
500 opacity animations are all the cheap kind. Why can they still be slow?
Cheap per animation is not free. The browser still works out 500 new values on every frame, which costs CPU. Memory and CPU are separate budgets, so check both.
Read more
Animating a blur: blurred copies at 1, 2, 4 and 8 px, cross-faded with opacity.
Page load and Core Web Vitals · Lesson 23 of 28 · about 10 minutes
Respond to clicks fast (INP)
A button can feel frozen even when its code runs quickly. You can find where a click waits and give the browser an earlier chance to show a response.
What you will learn
Find which part of a slow interaction takes the most time.
Split long work so the browser can handle input between pieces.
Show a change before doing work the user can wait for.
Where does the time after a click go?
A click can spend more time waiting to run than running its own code.
Walk through it
You click Sort while the page builds previews for another tab. The main thread runs page JavaScript and prepares screen updates. It finishes its current task, one unit of work, before it can run the code that handles your click.
Read the diagram from the click mark. Input delay covers the rest of the preview work. Processing time covers the click code, which sorts and updates the list. Presentation delay lasts until the next paint, when the browser draws the screen.
In this example the click waits 280 ms, then takes 60 ms to run and 20 ms to reach the next paint. With hundreds of notes, the preview build can dominate the wait.
Interaction to Next Paint (INP) describes responsiveness over a page visit. It uses one of the slowest clicks, taps or key interactions. On a visit with only a few interactions, it uses the slowest one.
The first bracket starts at the click. It counts only the part of the red preview work that the click waits for.
The fix
Record the click in your browser’s Performance panel and see which phase is longest. Build the previews when their tab opens, so Sort can run sooner during startup.
When processing or presentation takes most of the time, look at the click code and the browser’s drawing work before changing unrelated tasks.
Evidence
In one emoji picker, a user with about 20,000 custom emoji saw it freeze for about a second while one task built about 40,000 elements.
How can a long job give other clicks a turn?
Split work across tasks so input and paint can run in the gaps.
Walk through it
Someone opens Previews. If the browser builds all four previews in one task, a click during the first must wait for the rest.
Yielding ends the current task and lets the remaining work continue in another task. The diagram shows one possible schedule. Sort arrives during the first preview and the browser handles it and paints before starting the next preview.
With hundreds of previews, a pause between small groups keeps any one group from taking over for the whole build. Awaiting an already resolved promise queues a microtask, a short callback the browser runs before it can handle input or paint. Repeating that await keeps the work together from the browser’s point of view.
Red marks the waiting input. Green shows a possible time to handle Sort and paint between previews.
The fix
In an async handler, use scheduler.yield() when available or wait for a timer task. That gives the browser a turn before your function resumes.
// Before
for (const note of notes) buildPreview(note);
// After, inside an async handler
for (const note of notes) {
buildPreview(note);
await (globalThis.scheduler?.yield?.()
?? new Promise(resolve => setTimeout(resolve, 0)));
}
Watch out
Choose group sizes by measuring time on a slower device. Too many pauses stretch the total time, and one expensive item can still block input.
Check whether the user closed the tab or changed the notes while the job was paused before adding more previews.
Evidence
On one machine in the Node demo, replacing resolved promises with timer yields cut the delay before the test timer ran by about 280 ms.
What can wait until the screen responds?
Make the visible change first and give the browser a chance to draw it before running optional work.
Walk through it
Open an Edit dialog with a title field. Moving the typing cursor into that field can make the browser calculate element sizes and positions, which is called layout. Changing a style on the whole page can also make the browser check styles for many elements.
In the diagram, the first version opens the dialog and does both jobs before the browser can paint. The second version opens it and lets the browser paint before later work in this example. On a page with hundreds of elements, even one broad style change can slow that first frame.
Red is work holding up the first paint. In the second row the green paint mark can move earlier, although the focus and style work still happens.
The fix
Open the dialog and put keyboard focus on its Close button. Then ask for a requestAnimationFrame callback, which runs before a paint. Scheduling a timer from that callback gives the browser a chance to paint before the optional updates.
// Before, immediately after opening
titleField.focus();
document.body.classList.add('l23-editor-open');
// After, with Close focused on open
requestAnimationFrame(() => setTimeout(() => {
if (!dialog.open) return;
document.body.classList.add('l23-editor-open');
if (document.activeElement === closeButton) titleField.focus();
}, 0));
When closing a large panel, hide it first. Then remove its old elements in later tasks.
Watch out
Check in a recording when the browser actually draws.
Keep background clicks blocked while the dialog is open, even before the optional style runs. If users need to type immediately, focus the field when the dialog opens.
Evidence
On one site, INP fell by about half after changes that included hiding a banner before removing it.
Try it
Watch a timer wait
Run node demos/yield.js from the course folder. A timer stands in for the click, so the first result column measures timer delay in Node. Compare the one-task row with the resolved promise and timer rows. The last column shows when all the work finished.
Open the dialog with the keyboard
Tab to each Open button and press Enter. After the title gets focus, press Escape and check that focus returns to the button you used. On a repeat, try Tab or Escape immediately to check what happens when focus changes or the dialog closes early.
Remember
Start by finding the longest phase of the interaction.
Yield between pieces of work to let the browser handle input and paint.
Keep the visible change and required keyboard behavior in the opening task whenever you can.
Words used in this lesson
Term
Plain meaning
INP
A measure of how long a near-worst interaction takes to reach the next paint during a page visit.
Main thread
The part of the browser that runs page JavaScript and prepares screen updates.
Task
A unit of work such as a click handler or a timer callback.
Yield
Pause the job and let the browser start another task before the job continues.
Microtask
A callback that runs before the browser can take another task or paint.
Paint
The browser draws the next picture of the page.
Quick check
Sort takes little time, but the click lands during a preview build. Which phase grows?
Input delay grows because the main thread finishes the ongoing task before it can handle Sort. Shorter preview tasks give it more chances to respond.
Why does awaiting a resolved promise between previews leave clicks waiting?
Each continuation runs as a microtask, and the browser runs them all before it handles input or paints. A timer or scheduler.yield() gives it a chance between tasks.
Page load and Core Web Vitals · Lesson 24 of 28 · about 10 minutes
Show the first screen sooner
A page can stay blank while the browser waits for replies, or jump just as someone starts reading. You can shorten the chain of work before the first screen and reserve space for content that arrives later.
What you will learn
Follow the requests that hold up the first screen and remove one wait at a time.
Let the browser read the page while it downloads a script, and load optional code later.
Tell when the largest content appears and why other content can jump.
Which replies does the first screen have to wait for?
Start with the chain of replies the browser needs before it can show the first screen.
Walk through it
A shared link opens a note. A redirect sends the browser to a new address. The browser gets the HTML there and finds the script to download.
The script calls a data server at a different origin, which means its scheme, host or port differs. Because the request sends an Authorization header, the browser first asks for permission with an OPTIONS request called a CORS preflight. Once it has permission, it requests the note and can show it.
Each request and reply is a round trip. There are five in this example, and each waits for the last one. This chain is the critical path to the note appearing. More data can make each wait longer, especially over a slow connection.
The direct link skips the redirect. The same-origin API also skips the preflight. Read the blocks from left to right to see how each change moves the green end mark earlier.
The fix
First link straight to the note address. If you control both paths on the same origin, you can also serve the note at the old address. Then serve the data endpoint on the page’s origin, which removes the browser’s preflight for this request.
// Before: the server redirects this link
const noteLink = '/open-note/42';
const dataURL = 'https://api.example.com/notes/42';
// After: direct link and same-origin data endpoint
const noteLink = '/notes/42';
const dataURL = '/api/notes/42';
Watch out
Keep redirects that must change the scheme or host. Keep serving old shared links.
A server that forwards requests to the data service may add its own wait. Keep authentication in place and measure the full chain again.
Evidence
In one test on a mobile network, removing a redirect chain brought the first meaningful byte about 300 ms sooner.
Which scripts need to run while the page starts?
Let the browser read the first screen’s HTML and save optional scripts for when people use them.
Walk through it
A note page has a script above its title. The browser’s HTML reader, called the parser, pauses at the tag. It reads the title after the script downloads and runs.
With defer, the browser downloads that script while it keeps reading the HTML. In the diagram the script runs after reading ends. Paint, when the browser draws the screen, can still come afterward.
A script that handles one button may cost little. If it also loads export tools and every editor feature, the browser spends more time downloading and preparing code before the page is ready.
Red marks a pause in HTML reading. With defer the download overlaps reading and the green paint mark can move earlier.
The fix
Use defer when an external script can run after the HTML is read. Keep the note in the initial HTML when the server already has it. Client code can read that data with JSON.parse from a type="application/json" script tag.
For an optional Export button, load its code with import() on demand. This is code splitting, which puts the optional feature in a separate file. The first screen then skips its download and setup.
<!-- Before: the browser pauses reading for the script -->
<script src="/note-tools.js"></script>
<!-- After: the defer script sets up the existing button -->
<script src="/note-tools.js" defer></script>
// In note-tools.js, load export code when needed
exportButton.onclick = async () => {
const { openExport } = await import('./export.js');
openExport();
};
Watch out
If a deferred script creates the first screen, that screen still waits for the script to run.
When putting JSON inside HTML, escape literal < as \u003c in the serialized data. This keeps a value from closing the script tag.
Evidence
In an audit on a mid-range phone, running startup JavaScript took about five seconds.
When does the main content appear, and what makes it jump?
Start loading the main image early and tell the browser how much room to give it.
Walk through it
Imagine a page with a heading, a large photo and a paragraph. In the trace below, the heading appears first, so it is the biggest piece of visible content so far. When the larger photo appears, it takes over.
Largest Contentful Paint (LCP) measures how long it took from navigation for the largest eligible piece of visible content to appear. An image or a block of text can be that piece. In this example the visitor waits without interacting, so the photo supplies the final time.
The green bracket ends at the photo paint. The heading had already drawn during the download.
Now look at the paragraph in the next diagram. If the browser first gives the photo no room, the photo pushes the paragraph down when it arrives. Cumulative Layout Shift (CLS) scores the burst of unexpected movement with the most impact. Content that moves farther or takes up more of the screen can contribute a larger score.
The red paragraph drops. The green paragraph stays level because the photo fills the dotted space.
The fix
Put the image in the initial HTML so the browser finds it while reading the page. Give it its actual width and height so the browser can reserve space using the right shape.
<!-- Before: a script adds this after the app starts, with no size -->
<img src="photo.jpg" alt="A fern">
<!-- After: present in the initial HTML -->
<img src="photo.jpg" alt="A fern" width="600" height="300">
<style>img { max-width: 100%; height: auto; }</style>
Watch out
Keep the likely LCP image out of lazy loading, which delays the request until the browser decides the image is needed.
A fast photo can still move the text if its space was missing. Check both when the main content appears and where the text sits across successive frames.
Evidence
In the same audit, holding back scripts from other providers made the main content appear about one second sooner.
Remember
When one request starts only after another finishes, its wait adds to the chain.
Use defer to let HTML reading continue, and keep optional features out of startup.
Help the browser find the main image early and give it enough information to hold its place.
Words used in this lesson
Term
Plain meaning
Critical path
The chain of steps that decides the earliest the content can appear.
Round trip
One request and its reply.
Preflight
A browser request that asks whether it can make certain requests to another origin.
Defer
An instruction for an external script to run after the browser reads the HTML.
LCP
How long it took for the largest eligible piece of visible content to appear.
CLS
A score for the biggest burst of unexpected movement on the page.
Quick check
You removed the redirect, but the note request still waits. Where do you look next?
Check for a preflight before the data request. A request to another origin that sends an authorization header may need the extra permission check before requesting the data.
Does adding defer mean the page will paint before the script runs?
It means the script runs after the HTML has been read. The paint can come after the script, especially if the script builds the content.
The photo shows at the same time after you add dimensions, but the paragraph stays put. Which measure improves?
CLS improves if that movement contributed to the biggest burst of shifts. LCP stays the same in this example because the largest piece of content still appears at the same time.
TypeScript and tooling · Lesson 25 of 28 · about 10 minutes
Faster scripts and tests
A short command can spend most of its time loading files, and a small test can do extra work on the way to one check. You will learn to trim that work while keeping the command and the test doing their jobs.
What you will learn
Move an import to the command that uses it.
Make a test search less of the page while keeping the same check.
Skip browser requests that the test can do without.
Why does a tiny command take so long to start?
The ideaLoad each module when the command reaches the code that needs it.
Walk through it
A notes tool exports plain text or a PDF. Each writer lives in a module, a file that provides code another file can use. When Node first loads a module, it finds the file, reads and runs it, and loads the other files it asks for.
Suppose the PDF writer loads two helper files and the text writer loads none. If the entry file loads both writers before it checks the format, a text export loads four files beyond the entry file. The load diagram marks the three that a text export can skip.
Follow the arrows for one text export. Red files load for no benefit to this run. The green writer produces the output.
If the PDF writer and its helpers pull in 30 more files, choosing the text writer first skips all 33. The text writer does the same work once it starts.
The fix
Read the format first and load the matching writer inside that branch. This is lazy loading, which means waiting until the code needs a file before loading it.
// Before: both writers load on every run.
const pdf = require('./pdf');
const text = require('./text');
const writer = format === 'pdf' ? pdf : text;
writer.write(notes);
// After: load only the chosen writer.
if (format === 'pdf') require('./pdf').write(notes);
else require('./text').write(notes);
The same idea works in a VS Code extension, an add-on that runs inside the editor. An activation trigger such as onLanguage:typescript tells the editor to start the extension when a TypeScript file opens.
Watch out
Check whether an import sets up anything both commands need. Keep shared setup where both commands run it.
Time each format with a fresh process, because the first use of the PDF writer still has to load its files.
Evidence
Delaying and narrowing module loads saved about 40 milliseconds per run in one benchmark of npm run echo.
How much of the page does this test need?
The ideaKeep the checks that prove the behavior and cut setup or searching that adds nothing to them.
Walk through it
A page has a note form and a settings form. Each has two text fields. A test checks for the textbox named Title inside the note form.
getByRole looks for an element by its job, such as textbox. It can also match the accessible name, which is the name a screen reader would announce. The first diagram shows the candidates in the page's tree of elements, called the DOM.
The page search can consider all four boxes. The green form limits the search to two and leaves the red form outside it.
If each form grows to 50 fields, the scoped query has 50 textbox candidates instead of 100. It still checks the role and the name of the field it returns.
A browser test that checks whether Save adds a note also loads a preview image. Playwright usually waits for the page's load event, which fires after the page and its resources finish loading. If the image cannot affect Save, stopping its request can remove that wait, as the second diagram shows.
The red image request finishes after the green page code. When the request is blocked, the earlier vertical mark shows when the load event can fire.
The fix
Component tests usually run in Node with jsdom, a tool that imitates the browser's page structure (the DOM). Two small changes make these tests faster.
Use within(noteForm) to bind the query to the note form. In the browser test, use Playwright's page.route() to stop the preview request before the page loads.
// Testing Library, before
screen.getByRole('textbox', { name: 'Title' });
// Testing Library, after
within(noteForm).getByRole('textbox', { name: 'Title' });
// Playwright, before navigation
await page.route('**/previews/**', route => route.abort());
// Both versions still navigate and check that Save works.
await page.goto('/notes');
Watch out
Search the whole page if the test should catch duplicate controls anywhere on the page.
Keep the image request if Save depends on it or the test checks how the image appears.
Evidence
Changes to how jsdom finds elements and handles events cut the run time of one large form test by about 40 percent.
Remember
Choose the command before you load the code unique to it.
Search the smallest area where the test should find the control.
Block a browser request only when you can still prove the same behavior.
Words used in this lesson
Term
Plain meaning
Module
A file that provides code other files can use.
Lazy loading
The program waits until it needs code before it loads it.
DOM
The tree of elements that represents a page.
Accessible name
The name a screen reader uses for a control.
Quick check
What work does a text export skip when the PDF import moves?
The text export never reaches the branch that loads the PDF writer. That skips the writer itself and every file it alone would have loaded.
When should the title field test still search the whole page?
Keep the whole-page query if the test should fail when two textboxes named Title appear anywhere. A form query only checks the candidates inside that form.
Can a test of the preview image block its request?
The test needs the request because it checks whether the image appears. Blocking that request makes the page take a different path from the one the test should cover.
TypeScript and tooling · Lesson 26 of 28 · about 10 minutes
Faster type checking
A slow TypeScript run leaves you guessing whether the compiler is reading too many files or spending time on a few types. You will learn to find the expensive work and simplify the types that cause it.
What you will learn
Read the compiler's phase timings and follow a slow comparison to its source.
Use an interface to describe fields that always go together.
Use one shared shape when a function only needs shared fields.
Where does the compiler spend its time?
The ideaUse the timing summary to choose a phase, then follow a slow comparison to the types involved.
Walk through it
Suppose notes.ts passes a loaded note to two functions in cards.ts. First tsc, the TypeScript compiler, parses both files, which means turning their text into a tree it can read. Then it binds declarations, which means recording where names are defined.
While checking, the compiler compares types to see if values fit. For each call, it must ensure the loaded note has the fields the function's NoteProps type requires. Across hundreds of files, a timing summary tells you whether checking is where most of the time goes.
When Check time dominates, record a trace, a timeline of compiler work. In the diagram, a wide structuredTypeRelatedTo block shows a slow comparison. Here the target is NoteProps, the type the compiler is checking against.
Follow the target ID from the wide red span to the type entry, then open its declaration. The span widths illustrate time, without measured values.
The fix
Run the same compiler command with --extendedDiagnostics to see parse, bind, and check times. If parsing dominates and the file count surprises you, use --explainFiles to see why each file was included.
# Before: check types without writing JavaScript.
tsc -p tsconfig.json --noEmit
# After: show time per phase.
tsc -p tsconfig.json --noEmit --extendedDiagnostics
# If checking dominates, record a trace.
tsc -p tsconfig.json --noEmit --generateTrace ./tsc-trace
Open trace.json in a viewer that supports Chrome traces. Select the wide block and look at its sourceId and targetId. Find those IDs in types.json and follow firstDeclaration where it is present.
In this example, the target's declaration leads to NoteProps in cards.ts. Try the change in the next section and rerun the diagnostics command to see if Check time drops.
Watch out
Compare runs with the same files, compiler version, settings, and state of any saved results from earlier runs.
Use the trace to locate the slow work. Use the diagnostics run for timing because collecting a trace takes extra time.
Evidence
A draft change to simplify types in one React project cut the compiler's reported check time by about 14 seconds.
How can you make a type cheaper to check?
The ideaUse an interface for fields that go together and ask only for the fields a function reads.
Walk through it
NoteProps needs the fields from NoteMeta and Timestamps, plus a title. The intersection written with & asks for all three parts at once. To check a value against it, TypeScript can have to check the parts separately.
An interface names the fields an object must provide. With extends, it brings in the fields of other object types. In the comparison diagram, the first call still checks the fields, and the second can reuse the saved result for the same pair of types.
The red box shows extra comparisons the intersection can require. The green line shows reuse after the first check of this interface.
A union written with | accepts any of its member types. A function that reads just id may accept three kinds of notes through a union. To simplify a union, the checker may compare members in pairs to see which already fit other members.
Each red line marks one possible pair. The green path checks whether the argument has the field the function reads.
Three members give three possible pairs. With 50 members, there are 1,225 possible pairs because each member has 49 partners and each pair would otherwise count twice.
The fix
Give NoteProps one interface so the checker can reuse a comparison. Give noteId a shared type if any object with a string ID is valid input.
// Before
type NoteProps = NoteMeta & Timestamps & { title: string };
function noteId(note: DraftNote | PublishedNote | ArchivedNote) {
return note.id;
}
// After
interface NoteProps extends NoteMeta, Timestamps { title: string }
interface HasId { id: string }
function noteId(note: HasId) { return note.id; }
Watch out
Check accepted and rejected calls after the change. An interface can report a conflict where two base types define the same field differently.
Keep the union if callers must pass only those note kinds. Test inline object literals because a shared shape can reject fields it omits.
Evidence
TanStack Table's core saw about 80 percent fewer type instantiations, or computations from type templates, after several changes including an interface rewrite.
Try it
Pick a TypeScript project where checking feels slow and run the diagnostics command from that project. Look at the check and parse times, then follow one slow comparison if checking is where the time goes.
Remember
Read phase timings before changing types.
Follow the trace from a slow comparison to the types it checks.
Verify the same useful calls still work and measure check time again.
Words used in this lesson
Term
Plain meaning
Trace
A record of what the compiler does and how long each recorded step takes.
Intersection
A type that requires all its parts to fit.
Interface
A named description of the fields an object must provide.
Union
A type that accepts any one of its members.
Type instantiation
The checker works out a type after you fill in a placeholder, such as putting Note in Array<Note>.
Quick check
Check time is small and the compiler parses far more files than expected. Where do you start?
Run --explainFiles to see why each file is included. The reported time points to reading and parsing the project's files, so investigate that work first.
Can the checker reuse the result on the first comparison against a new interface?
It has to compare the two types before it has a result to save. A later check of the same pair can use that result.
When is HasId too broad for noteId?
It is too broad if the function should accept only the three kinds of notes. The shared shape would also accept a user with a string ID.
Engine internals · Lesson 27 of 28 · about 10 minutes
Object shapes and inline caches
The JavaScript engine reads a property quickly only when it can predict where that property sits inside the object. After this lesson you can build objects so a hot loop stays predictable, and spot the habits that quietly break it.
What you will learn
Why two objects with the same fields can still look different to the engine, and why delete hurts.
How one property read remembers the objects it has seen, and why a fifth kind of object can make it several times slower.
Why do two objects with the same fields look different to the engine?
The idea
Objects built with the same fields in the same order share one hidden layout, so the engine reads a field by position instead of searching for it by name.
Walk through it
This lesson uses V8, the engine inside Chrome and Node.js. An object looks like a bag of names and values, but searching a bag by name on every read would be slow. So V8 gives each object a hidden class, a shared description of its layout. V8 calls it a map, and other engines call it a shape.
A map says which slot holds each field, for example "x is in slot 0, y is in slot 1". The object itself stores only the values, plus a pointer to its map. When V8 knows the map, reading p.y becomes "go to slot 1", with no search at all.
Maps grow one field at a time. Start from an empty object and add x, and you move to a map that has x. Add y and you move to a map with x, then y. Each step is called a transition. V8 remembers it, so the next object built the same way lands on the same map.
Take three points. Points a and b are built as { x, y }, and c is built as { y, x }. In the diagram, a and b take the top path and share one map. Object c adds y first, so it takes the bottom path and ends on a different map, even though it has the same two fields.
Follow the arrows from the empty object. Same order, same path, same map; c took the other branch, so its slots are swapped. Simplified: real maps hold more detail.
Now scale it up. If 10,000 rows are built by one function, they share one map. If they are built in three places with three field orders, there are three maps. Adding a field later, as in if (vip) row.discount = 0.1, splits them again.
The delete operator is worse. Removing a field usually makes V8 give up on maps for that object and switch it to dictionary mode. The object gets its own private table of names and values, so every read becomes a search by name. In the second diagram, only the right object still uses the shared map.
Top: after delete, the row keeps its own private table. Bottom: the slot stays and holds undefined, so the row still points at the map every other row uses. Illustrative.
The fix
Build each kind of object in one small factory that writes every field in the same order. Store null or undefined for a field with no value, and set a field to undefined instead of deleting it.
These three are not the same to your code. A missing field is skipped by Object.keys and the in operator. A field set to undefined still shows in Object.keys, but JSON.stringify leaves it out. A field set to null shows up everywhere, JSON included.
// Before: the shape depends on which branch ran, and delete leaves the map
const row = { id: item.id, draft: true };
if (item.sale) row.discount = item.sale.pct;
delete row.draft;
// After: one factory, every field, same order
const makeRow = (item) => ({ id: item.id, draft: true, discount: item.sale?.pct ?? 0 });
const row = makeRow(item);
row.draft = undefined; // the slot stays, so the map stays
Watch out
Copying without the field (const { draft, ...rest } = row) also avoids delete. But it allocates a new object, and any code holding the old object still sees draft.
A map also records what kind of value each field has held. Start number fields as numbers, not as null. A field that will hold decimals should start as a decimal.
Evidence
In TanStack Start's server rendering, replacing one delete with an assignment to undefined cut that function's CPU time by more than half.
Why can a fifth kind of object make a loop several times slower?
The idea
Each property read keeps a tiny cache of the maps it has seen, and once that cache overflows, every read falls back to a much slower general lookup.
Walk through it
Take total += item.price inside a loop. V8 attaches a tiny memory to that one read, called an inline cache. It stores pairs of map and slot, such as "if the item has map A, price is in slot 1".
Say items come from two places. Items built as { name, price } have map A, with price in slot 1. Items built as { price, name } have map B, with price in slot 0. In the diagram, an item with map B arrives. The cache checks map A first and fails, then checks map B and matches, so it loads slot 0.
The cache is checked top to bottom. One check fails, one matches, and the matched entry says which slot to load.
A read site that has seen only one map is monomorphic, meaning one form: one check, then a direct load. With two to four maps it is polymorphic, meaning several forms, and it checks them in turn. That is a little slower.
In the V8 version measured here, the list holds four maps. A fifth makes the site megamorphic, meaning many forms. V8 stops keeping a list. It looks the property up in one big table shared by the whole program, which is far more work. The limit of four is version-specific and can change.
The demo sums .x over 1,000 objects of a chosen number of shapes, 20,000 times. That is 20 million reads through one read site. In the chart, one to four shapes stay close. The fifth makes the same loop about three and a half times slower than four.
Measured with demos/ic-cliff.js on Node 22.19, one machine. Look at the jump across the dashed line. The limit is version-specific, so other Node versions may jump at a different count.
The fix
Turn objects into one shape at the edge, before they reach the hot loop. A factory that always writes the same fields in the same order gives every item one map, so the read site stays monomorphic.
// Before: items from three sources reach the hot loop in their own layouts
const all = [...cartItems, ...savedItems, ...importedItems];
// After: one factory, so every item shares one map
const toItem = (s) => ({ id: s.id, price: s.price, qty: s.qty ?? 1 });
const all = [...cartItems, ...savedItems, ...importedItems].map(toItem);
let total = 0;
for (const item of all) total += item.price * item.qty; // one map seen here
Watch out
Two to four shapes are usually fine. Only fight for one shape when a profile shows the loop is hot.
The copy costs time and memory too. Time the whole job, copy included, before and after.
Evidence
A TypeScript prototype that gave all syntax tree nodes one layout cut total compile time by about 16 percent, for about 3 percent more memory.
Try it
Try it (2 minutes)
From the course folder, run node --allow-natives-syntax demos/shapes.js. The flag unlocks V8's internal test functions. Look for true only on the same-order line, and for the deleted object reporting no fast properties. The added-later line is false too, so create objects with every field at once.
Then run node demos/ic-cliff.js 4 and node demos/ic-cliff.js 5. Look for the time jumping to about three and a half times as much when the fifth shape arrives.
Remember
Create each kind of object in one place, with every field present, in the same order. Do not delete fields in hot code.
A read site that sees more maps than its cache holds (four in current V8) goes megamorphic and can run several times slower. Normalise objects before the hot loop.
This matters only for objects that flow through hot code by the thousand, after a profile points there.
Words used in this lesson
Term
Plain meaning
Hidden class, map, shape
A shared description of an object's layout that says which slot each field is in.
Transition
The step from one map to the next when a field is added. Same steps give the same map.
Dictionary mode
An object with its own private table of names instead of a shared map, so every read searches by name.
Inline cache
A tiny memory on one property read that remembers which maps it has seen and their slots.
Monomorphic, polymorphic, megamorphic
A read site that has seen one map, a few maps (up to four in current V8), or more than its cache holds.
Quick check
Do { x: 1, y: 2 } and { y: 2, x: 1 } share a map? Why does it matter?
No. Each object walks its own chain of transitions, so x first and y first end on different maps, and the demo prints false. A function that reads .x from both now sees two maps, so its inline cache is polymorphic instead of monomorphic.
A loop that sums item.price got about three times slower after items from two more sources were added. What probably happened?
The read site probably went from four or fewer maps to five or more, so its inline cache turned megamorphic. Each read now uses a slow shared lookup instead of a quick map check. Map every item through one factory before the loop, then time the whole job, copy included.
Why set a field to undefined instead of using delete, and what changes for your code?
Setting it keeps the slot, so the object stays on its shared map, while delete usually pushes it into dictionary mode. The key is still there, though: Object.keys and in still see it. Use delete only where the key must truly disappear.
Read more
V8: hidden classes: the official explainer of maps and transitions, with diagrams.
Engine internals · Lesson 28 of 28 · about 10 minutes
Deopts and what your build emits
The engine's fast code rests on guesses, and the code that actually runs is often not the code you wrote. After this lesson you can see when V8 throws its fast code away, and check what your build turns your loops into.
What you will learn
Why V8 throws optimised code away, and how to watch it happen.
What an old build target does to a for...of loop.
Why newer syntax is sometimes the slower one, and how to decide.
Why does V8 throw its fast code away?
The idea
Optimised code is built on a guess about the objects it will see, and when an object breaks the guess, V8 drops the fast code and goes back to the slow interpreter.
Walk through it
V8 first runs a function in an interpreter, which is slow but records what it sees, such as "every argument had map A". This record is called type feedback. Once the function is hot, an optimising compiler turns it into machine code that assumes the feedback stays true.
Take getX(p), which returns p.x. After many calls with { x } objects, the fast version is short: check that the map is A, then load slot 0. That check is called a guard, because it protects the guess.
Now a { y, x } object arrives, with map B. The guard fails, so the fast code cannot continue safely. V8 jumps back to the interpreter in the middle of the call. This is a deoptimisation, or deopt, also called a bailout.
In the diagram, time runs top to bottom. The green box is the fast code. At the red arrow the guard fails, and the function drops back to the slow lane. It records map B as well, and V8 may compile it again later with two checks.
The red arrow is the bailout: the fast code is dropped mid-call. Simplified: V8 has several tiers, and when and how it optimises changes between versions.
One deopt costs little. The problem is a hot function that keeps meeting new shapes, so it bails out, recompiles and bails out again.
The fix
Give hot functions stable inputs by building their objects in one factory, as in lesson 27. Then confirm with --trace-deopt, which prints a line each time V8 bails out, with the function name and the reason.
// Before: two creation sites, two key orders
const a = { x: 1, y: 2 };
const b = { y: 3, x: 4 }; // map B reaches getX: bailout
// After: one factory, one map
const point = (x, y) => ({ x, y });
const a = point(1, 2), b = point(4, 3);
// Check: node --trace-deopt app.js 2>&1 | grep bailout
Watch out
A few deopts during warm-up are normal. Worry only when the same hot function bails out again and again.
Optimisation rules change between V8 versions, so check on the Node version you ship.
Evidence
In one open-source query engine, giving every change event one fixed layout made hot query paths up to 18 percent faster.
What does your build do to a for...of loop?
The idea
If your build target is older than the runtime you ship to, the compiler rewrites modern syntax into helper code that runs on every loop step.
Walk through it
A build tool such as TypeScript or Babel can downtranspile your code. That means rewriting new syntax into older syntax, so it runs on old browsers. The oldest version it must support is the build target, such as ES5 (from 2009) or ES2020.
ES5 has no for...of, so the loop must be rebuilt from older parts. In the first diagram, the top box is the three lines you wrote. The bottom box is a simplified version of what a Babel-style ES5 build ships.
The red band runs once per item: a helper call, a new result object, a done check and a read of value. The helper name is simplified.
Follow one step. The helper it.n() is called, it creates a small result object holding value and done, the loop checks done, and then it reads value. A plain index loop only compares i with the length and reads items[i]. The second diagram puts the two side by side.
Two small steps against four, one of which makes garbage. Simplified: the engine can sometimes remove part of this cost.
Now scale it up. A loop over 10,000 items makes 10,000 helper calls and up to 10,000 throwaway objects. The engine can sometimes optimise this away, but profiles of real libraries show the cost often stays.
The fix
Set the build target to the oldest runtime you really support. Current Node versions and current browsers run ES2020 syntax natively, so a modern target ships for...of, classes and let as written.
// tsconfig.json before: every for...of goes through a helper
{ "compilerOptions": { "target": "ES5", "downlevelIteration": true } }
// after: the loop ships as written
{ "compilerOptions": { "target": "ES2020" } }
Watch out
Libraries ship their own build. Read the file your app loads from node_modules, not the source on GitHub.
If you must support an old target, write the hot loop as a plain index loop, so there is nothing to rewrite.
Evidence
In esquery, which ESLint uses to match code patterns, avoiding the downtranspiled for...of saved about 2 seconds of a lint run.
Is the newest syntax always the fastest?
The idea
No: sometimes the older form runs faster, and the winner changes between engines and versions, so measure the built file on the runtime you ship.
Walk through it
Native for...of still uses the iterator protocol underneath. graphql-js moved its build target from ES5 to ES2020, and its hot loops over Map entries now ran through that protocol. Building a schema then ran about 22 percent fewer times per second, although later reruns gave mixed results. The whole new build caused that, not only the loops.
let and const come with a check that a variable is not read before its declaration has run. That window is called the temporal dead zone (TDZ). In TypeScript's own huge compiler file, V8 could not always skip those checks, so the team changed the hottest variables to var by hand.
The chart shows an experiment that turned every let and const into var. It cut parse time in one benchmark from 3.93 to 3.52 seconds on Node 18. On Bun, which uses a different engine, there was no difference. Preact's signals library made a similar call, turning its classes into plain functions with prototype methods because they were faster in its benchmark.
The bars are Node 18 (V8), from one benchmark in the TypeScript pull request. The same change did nothing on another engine.
So none of these is a rule. Each result is one engine, one version and one hot path.
The fix
Do not rewrite a whole codebase in old syntax. Profile the built output, find the one hot loop, and write it in a plain form that every target handles the same way.
// Before: a hot loop that goes through the iterator protocol
for (const [key, value] of map.entries()) use(key, value);
// After (the graphql-js approach): an index loop over a plain array
const entries = Array.from(map.entries());
for (let i = 0; i < entries.length; i++) {
const { 0: key, 1: value } = entries[i];
use(key, value);
}
Watch out
var ignores blocks, so it can leak out of loops and if bodies. Keep tricks like this for compilers and parsers that run billions of steps.
Re-measure after each Node or browser upgrade, because these gaps open and close between versions.
Evidence
In an experiment, switching TypeScript's compiler to var cut parse time by about 10 percent on Node 18.
Try it
Try it (1 minute)
From the course folder, run node --allow-natives-syntax --trace-deopt demos/deopt.js 2>&1 | grep bailout. The demo forces getX to be optimised for { x } objects, then passes it a { y, x } object. Look for a line starting with [bailout that names getX, with a reason such as wrong map. The exact wording varies between Node versions.
Remember
A new shape fails the guard in optimised code, so V8 bails out. One bailout is fine, but repeated ones are not.
Check your build target. An old target turns for...of into helper code that runs on every step, and classes into helper calls.
Old versus new syntax has no fixed winner. Measure the built file on the engine and version you ship.
Words used in this lesson
Term
Plain meaning
Type feedback
What the interpreter records while running a function, such as which maps each read has seen.
Optimising compiler
The part of V8 that turns a hot function into fast machine code built on that feedback.
Guard
A quick check inside optimised code that the guess still holds, such as "is this map A?".
Deoptimisation, deopt, bailout
Dropping the fast code when a guard fails and going back to the interpreter mid-call.
Build target, downtranspile
The oldest JavaScript version your build must support, and rewriting newer syntax into it.
Temporal dead zone (TDZ)
The time before a let or const line runs, when reading the variable is an error.
Quick check
A function was fast for a million calls, then got slow after a new data source was added. --trace-deopt shows it bailing out again and again. What happened?
The optimised code had a guard for the maps it had seen. Objects from the new source have a different map, so the guard fails and V8 drops back to the interpreter, more than once. Normalise the new objects into the same shape before they reach the function.
Your library's hot loop uses for...of, and its build target is ES5. Why might users see it slower than your tests on the source?
An ES5 target cannot ship for...of, so the build swaps in helper code. That code calls a function and makes a result object for every item. Your tests ran the source, not that output. Raise the target, or write the hot loop as an index loop.
Someone proposes changing every let in an app to var for speed. What do you say?
The TypeScript gain came from a huge compiler running billions of steps, on one engine, and Bun showed no difference. For app code the saving is unlikely to show, while var adds scoping bugs. Profile first, and change only a measured hot spot.
Read more
rocicorp/mono #5801: four change-event shapes replaced by one fixed tuple layout.
esquery #134: hot-path fixes, including avoiding downtranspiled for...of.
graphql-js #3687: index loops after a move from an ES5 to an ES2020 target.