Measure before you optimise
Before you fix a slow page, find out which step is slow. The browser and React come with measuring tools: named marks, the React Profiler and long-animation-frame reports. We use all three on one slow page and find two different problems - neither of them JSON.parse.
What you will be able to do
- Name the steps of a page load with performance.mark
- Time React’s rendering with the <Profiler> component - and know why it is silent in a normal production build
- Read a long-animation-frame entry: script time, style and layout time, and which script ran
- Confirm a suspect with a small test on its own before changing the app
- Choose a fix only after the numbers say which step is slow
The idea, in plain English
In Lesson 1.1 we saw that one page load is several steps on the main thread: download, parse, React render, layout and paint. When a page is slow, the first question is not “how do I make it faster?” but “which step is slow?”. A guess is often wrong, and a fix for the wrong step changes nothing.
You do not need to write a timer for everything. The browser and React already measure a lot: performance.mark() and performance.measure() name the steps of your own code; React’s <Profiler> reports how long React spent rendering a part of the tree; and the Long Animation Frames API (LoAF) reports every frame over 50 ms, split into script time and style + layout time, with the script that started it.
We use all three on one page - 10,000 orders, each total shown as rupees - in headless Chromium 159.0.8154.6 through playwright-core 1.65.1, with React 19.2.3 bundled by esbuild 0.28.1, on the same Intel Core i5-4200U laptop (4 threads, 7 GB RAM) as Lesson 1.1. Every case ran 5 times and the numbers are medians. The small formatter test runs in Node.js 26.12.1.
Worked example: A page that shows 10,000 orders with their totals as rupees. Marks, the Profiler and long-animation-frame reports split its load into parse, React and layout - and point to a one-line fix.
1 - The guess: JSON.parse
The marks say the parse of 10,000 orders is tiny. Making it faster would change almost nothing.
10,000 orders, median of 5 runs. Real results from run2.mjs (profiling build).
Words you will see in this lesson
A few measuring words.
performance.mark(name)Saves a named point in time. The DevTools Performance panel shows marks too.performance.measure(name, start, end)The time between two marks, saved under a name.React ProfilerA <Profiler> component that calls onRender with how long React spent rendering its children.Profiling buildA production version of react-dom with the Profiler switched on: react-dom/profiling.Long animation frame (LoAF)A frame that took over 50 ms. The browser reports its script time, its style + layout time, and the scripts that ran.Blocking durationThe part of a long frame that blocked input: everything over 50 ms in each long task.SuspectThe piece of code you think is slow - before you have proved it.An everyday example: a slow kitchen
- Dinner at a restaurant takes an hour. The owner guesses the chef is slow and buys a faster stove.
- Nothing changes - because the food was ready in ten minutes and waited forty minutes for a waiter.
- A stopwatch at each step (order taken, cooked, served) would have shown it at once.
- performance.mark, the Profiler and LoAF are those stopwatches for your page.
Example 1 - a page that measures itself
app2.jsx is the orders table from Lesson 1.1 with one change - each total is shown as rupees - and three measuring tools built in:
- performance.mark("start"), ("downloaded"), ("parsed"), ("committed") and ("painted") name the steps. Later, performance.getEntriesByName("parsed") reads them back.
- <Profiler id="OrderTable" onRender={onRender}> wraps the table. React calls onRender after each render with actualDuration - the time React spent rendering what is inside.
- A PerformanceObserver for "long-animation-frame" collects every frame over 50 ms. Each entry has duration, blockingDuration, styleAndLayoutStart and a scripts list.
- formatMoney() is the suspect. Without ?fix=1 it calls toLocaleString with currency options for every row; with ?fix=1 it uses one Intl.NumberFormat made once.
// Lesson 1.2: a slow page, measured with the browser's and React's own tools.
// ?n=10000 the orders file to load
// ?fix=1 format money with one shared Intl.NumberFormat
import { Profiler, useLayoutEffect, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
const params = new URLSearchParams(location.search);
const url = "/orders-" + params.get("n") + ".json";
const fixed = params.get("fix") === "1";
// 1. Long Animation Frames: the browser reports every frame that took over 50 ms,
// split into script time and style + layout time, with the scripts that ran.
window.frames = [];
new PerformanceObserver((list) => {
for (const f of list.getEntries()) window.frames.push(f.toJSON());
}).observe({ type: "long-animation-frame", buffered: true });
// 2. React Profiler: how long React spent rendering this part of the tree.
window.renders = [];
function onRender(id, phase, actualDuration, baseDuration) {
window.renders.push({ id, phase, actualDuration, baseDuration });
}
const money = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
function formatMoney(value) {
if (fixed) return money.format(value); // one formatter, made once
return value.toLocaleString("en-IN", { style: "currency", currency: "INR" }); // a new one every call
}
function OrderRow({ order }) {
return (
<tr>
<td>{order.id}</td>
<td>{order.customer}</td>
<td>{order.city}</td>
<td>{order.status}</td>
<td>{formatMoney(order.total)}</td>
<td>{order.items.length}</td>
</tr>
);
}
function OrderTable({ orders }) {
useLayoutEffect(() => {
performance.mark("committed");
requestAnimationFrame(() =>
setTimeout(() => {
performance.mark("painted");
window.done = true;
}),
);
}, []);
return (
<table>
<tbody>
{orders.map((order) => (
<OrderRow key={order.id} order={order} />
))}
</tbody>
</table>
);
}
function App() {
const [orders, setOrders] = useState(null);
useEffect(() => {
(async () => {
// 3. User Timing: named marks, shown in the DevTools Performance panel too.
performance.mark("start");
const res = await fetch(url);
const text = await res.text();
performance.mark("downloaded");
const data = JSON.parse(text);
performance.mark("parsed");
setOrders(data);
})();
}, []);
return (
<Profiler id="OrderTable" onRender={onRender}>
{orders ? <OrderTable orders={orders} /> : <p>Loading orders…</p>}
</Profiler>
);
}
createRoot(document.getElementById("root")).render(<App />);Two builds: the Profiler needs react-dom/profiling
In a normal production build React removes the Profiler’s timing code to stay fast, so onRender is never called. To profile production code, bundle the profiling version of react-dom instead. build2.sh makes both bundles from the same app2.jsx:
#!/usr/bin/env bash
# Two bundles of the same page: the normal production build, and the production build
# with React's profiling version of react-dom (needed for <Profiler> in production).
set -e
node_modules/.bin/esbuild app2.jsx --bundle --minify --jsx=automatic \
--define:process.env.NODE_ENV='"production"' --log-level=warning \
--outfile=public/app2.js
node_modules/.bin/esbuild app2.jsx --bundle --minify --jsx=automatic \
--define:process.env.NODE_ENV='"production"' --log-level=warning \
--alias:react-dom/client=react-dom/profiling \
--outfile=public/app2-profiling.jsTip: In development (npm run dev) the Profiler always works, and the React DevTools browser extension shows the same numbers per component. But development React is much slower than production, so measure the real speed in a production or profiling build.
Example 2 - reading the tools
run2.mjs opens the page in headless Chromium, waits until it is painted, and reads what each tool recorded. It runs three cases: the normal build, the profiling build, and the profiling build with the fix:
- at(name) reads a mark’s time; the differences give parse, React render + commit, and layout + paint.
- From the long-animation-frame entries it takes the longest frame: its script time is the sum of its scripts, and its style + layout time runs from styleAndLayoutStart to the end of the frame.
- From the Profiler it takes the biggest render - the one that drew the table. (The first render only drew “Loading orders…”.)
- Each case runs 5 times, in a fresh tab, and prints the medians.
// Lesson 1.2: load the page in headless Chromium and read what each tool reports.
// node run2.mjs [runs]
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { chromium } from "playwright-core";
const RUNS = Number(process.argv[2] || 5);
const exe = fs.globSync(os.homedir() + "/.cache/ms-playwright/chromium_headless_shell-*/*/chrome-headless-shell")[0];
const server = http
.createServer((req, res) => {
const file = path.join("public", new URL(req.url, "http://x").pathname);
res.writeHead(200, { "content-type": file.endsWith(".json") ? "application/json" : file.endsWith(".js") ? "text/javascript" : "text/html" });
fs.createReadStream(file).pipe(res);
})
.listen(0);
const base = "http://127.0.0.1:" + server.address().port;
const browser = await chromium.launch({ executablePath: exe });
async function once(page, query) {
const tab = await browser.newPage();
await tab.goto(base + "/" + page + ".html?" + query);
await tab.waitForFunction(() => window.done, null, { timeout: 300_000, polling: 100 });
const r = await tab.evaluate(() => {
const at = (name) => performance.getEntriesByName(name)[0].startTime;
// The longest animation frame, and how its time splits up
const f = window.frames.sort((a, b) => b.duration - a.duration)[0];
const script = f.scripts.reduce((sum, s) => sum + s.duration, 0);
const top = f.scripts.sort((a, b) => b.duration - a.duration)[0];
// The biggest render: the one that drew the table (the first one only drew "Loading")
const biggest = window.renders.sort((a, b) => b.actualDuration - a.actualDuration)[0];
return {
parse: at("parsed") - at("downloaded"),
reactCommit: at("committed") - at("parsed"),
layoutPaint: at("painted") - at("committed"),
profiler: biggest ? biggest.actualDuration : null,
profilerPhase: biggest ? biggest.phase : "-",
profilerCalls: window.renders.length,
frame: f.duration,
frameBlocking: f.blockingDuration,
frameScript: script,
frameStyleLayout: f.startTime + f.duration - f.styleAndLayoutStart,
topScript: top.invoker + " (" + top.invokerType + ")",
longFrames: window.frames.length,
domNodes: document.getElementsByTagName("*").length,
};
});
await tab.close();
return r;
}
const median = (xs) => {
const s = xs.filter((x) => typeof x === "number").sort((a, b) => a - b);
return s.length ? s[Math.floor(s.length / 2)] : xs[0];
};
const ms = (v) => (v === null ? "-" : Math.round(v).toLocaleString("en-US") + " ms");
console.log("browser " + browser.version() + " | median of " + RUNS + " runs, 10,000 orders");
const all = {};
for (const [page, query] of [
["app2", "n=10000"],
["app2-profiling", "n=10000"],
["app2-profiling", "n=10000&fix=1"],
]) {
const runs = [];
for (let i = 0; i < RUNS; i++) runs.push(await once(page, query));
const m = Object.fromEntries(Object.keys(runs[0]).map((k) => [k, median(runs.map((r) => r[k]))]));
all[page + "?" + query] = { runs, median: m };
console.log("");
console.log(page + "?" + query);
console.log(" marks parse " + ms(m.parse) + " | React render + commit " + ms(m.reactCommit) + " | layout + paint " + ms(m.layoutPaint));
console.log(" Profiler biggest render " + ms(m.profiler) + " (" + m.profilerPhase + ")" + " (onRender called " + m.profilerCalls + " times)");
console.log(" LoAF longest frame " + ms(m.frame) + ": script " + ms(m.frameScript) + ", style/layout " + ms(m.frameStyleLayout) + " | blocking " + ms(m.frameBlocking) + " | top script: " + m.topScript);
console.log(" DOM " + m.domNodes.toLocaleString("en-US") + " nodes | long frames " + m.longFrames);
}
fs.writeFileSync("results2.json", JSON.stringify(all, null, 1));
await browser.close();
server.close();browser 159.0.8154.6 | median of 5 runs, 10,000 orders
app2?n=10000
marks parse 17 ms | React render + commit 623 ms | layout + paint 1,318 ms
Profiler biggest render - (-) (onRender called 0 times)
LoAF longest frame 1,919 ms: script 621 ms, style/layout 1,298 ms | blocking 1,869 ms | top script: MessagePort.onmessage (event-listener)
DOM 70,009 nodes | long frames 2
app2-profiling?n=10000
marks parse 17 ms | React render + commit 670 ms | layout + paint 1,250 ms
Profiler biggest render 642 ms (update) (onRender called 2 times)
LoAF longest frame 1,897 ms: script 668 ms, style/layout 1,227 ms | blocking 1,847 ms | top script: MessagePort.onmessage (event-listener)
DOM 70,009 nodes | long frames 2
app2-profiling?n=10000&fix=1
marks parse 15 ms | React render + commit 226 ms | layout + paint 1,300 ms
Profiler biggest render 195 ms (update) (onRender called 2 times)
LoAF longest frame 1,500 ms: script 225 ms, style/layout 1,279 ms | blocking 1,450 ms | top script: MessagePort.onmessage (event-listener)
DOM 70,009 nodes | long frames 2Reading the output
- JSON.parse took 15-17 ms in every case. It is not the problem at 10,000 orders.
- Normal build: the Profiler printed nothing - onRender was called 0 times. The marks still worked: React render + commit 623 ms, layout + paint 1,318 ms.
- Profiling build: the Profiler saw a 642 ms render. React render + commit took 670 ms here against 623 ms in the normal build - the profiling build is a little slower, because it measures.
- Long animation frame: the longest frame lasted 1,897 ms - script 668 ms and style + layout 1,227 ms. So the browser’s layout work was about twice React’s work.
- Top script: MessagePort.onmessage. That is not our fetch code - it is React’s scheduler, which runs renders from a MessageChannel message. So the script time is React rendering.
- Two problems, then: React’s render (642 ms) and layout (1,227 ms). Next we find out why the render is slow.
Example 3 - test the suspect on its own
The Profiler says the table’s render is slow, and the only new thing in each row is formatMoney(). Before changing the app, test that suspect alone - no React, no DOM - with three ways to turn 10,000 totals into text:
- toLocaleString with a locale and options took 532 ms for 10,000 numbers. Each call builds a new formatter: it loads the rules for that locale and currency, then throws them away.
- One Intl.NumberFormat, made once, took 15 ms for the same numbers.
- The text is the same (“same text? true”), so the fix changes nothing the user sees.
- toFixed(2) is faster still (2 ms) but cannot add the ₹ sign or Indian digit grouping.
// Is formatting money really slow? Test the suspect alone, outside React and the DOM.
const totals = Array.from({ length: 10000 }, (_, i) => i * 1.37);
function time(label, fn) {
const runs = [];
for (let r = 0; r < 5; r++) {
const t0 = performance.now();
for (const total of totals) fn(total);
runs.push(performance.now() - t0);
}
runs.sort((a, b) => a - b);
console.log(label.padEnd(44) + runs[2].toFixed(0).padStart(5) + " ms (median of 5)");
}
const money = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
time("toLocaleString('en-IN', currency) x 10,000", (t) => t.toLocaleString("en-IN", { style: "currency", currency: "INR" }));
time("one Intl.NumberFormat, .format() x 10,000", (t) => money.format(t));
time("toFixed(2) x 10,000", (t) => t.toFixed(2));
console.log("same text?", (1234.5).toLocaleString("en-IN", { style: "currency", currency: "INR" }) === money.format(1234.5), money.format(1234.5));toLocaleString('en-IN', currency) x 10,000 532 ms (median of 5)
one Intl.NumberFormat, .format() x 10,000 15 ms (median of 5)
toFixed(2) x 10,000 2 ms (median of 5)
same text? true ₹1,234.50Before and after: one shared formatter
The fix is one line in formatMoney(): use the money formatter made at the top of the file. Both runs below use the profiling build:
- Profiler: the table’s render fell from 642 ms to 195 ms.
- Marks: React render + commit fell from 670 ms to 226 ms.
- Long frame: from 1,897 ms to 1,500 ms - but style + layout stayed at about 1,279 ms.
- The page is better, not fast: 70,009 DOM nodes still need layout. That cost only goes away when fewer rows are in the DOM - Module 2.
return value.toLocaleString("en-IN", { style: "currency", currency: "INR" });const money = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
// ...
return money.format(value);app2-profiling?n=10000
marks parse 17 ms | React render + commit 670 ms | layout + paint 1,250 ms
Profiler biggest render 642 ms (update) (onRender called 2 times)
LoAF longest frame 1,897 ms: script 668 ms, style/layout 1,227 ms | blocking 1,847 ms | top script: MessagePort.onmessage (event-listener)
DOM 70,009 nodes | long frames 2
app2-profiling?n=10000&fix=1
marks parse 15 ms | React render + commit 226 ms | layout + paint 1,300 ms
Profiler biggest render 195 ms (update) (onRender called 2 times)
LoAF longest frame 1,500 ms: script 225 ms, style/layout 1,279 ms | blocking 1,450 ms | top script: MessagePort.onmessage (event-listener)
DOM 70,009 nodes | long frames 2Watch out: Without the measurements, both fixes are easy to get wrong: a faster JSON parser would save almost nothing here, and the formatter fix alone would leave the biggest cost - layout - untouched.
A habit: measure, find, fix, measure again
- Measure: marks around your own steps, the Profiler around the slow part of the tree, LoAF for the frames.
- Find: the step with the biggest number. Then find the suspect inside it.
- Prove: test the suspect alone, like formatters.mjs.
- Fix one thing, and measure again with the same script - the after numbers are the proof.
- Keep the script: it tells you when a later change makes the page slow again.
Measuring tools at a glance
Name a point in timeShown in the DevTools Performance panel.
performance.mark("parsed")Read a mark backIts time in ms since the page started.
performance.getEntriesByName("parsed")[0].startTimeTime React’s workNeeds development or react-dom/profiling.
<Profiler id="Table" onRender={(id, phase, actualDuration) => ...}>Long framesEvery frame over 50 ms, with script and layout times.
new PerformanceObserver(cb).observe({ type: "long-animation-frame", buffered: true })Layout part of a frameStyle + layout time.
frame.startTime + frame.duration - frame.styleAndLayoutStart
DOM sizeElements on the page.
document.getElementsByTagName("*").lengthTry it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Wrap only one OrderRow in its own <Profiler id="row">. How long does one row take to render, with and without ?fix=1?”
“Add a date to each order and show it with new Date(...).toLocaleDateString("en-IN", { dateStyle: "medium" }). Does formatters.mjs show the same problem for dates?”
“Add the case ["app2", "n=10000&fix=1"] to run2.mjs. How much faster is the normal build than the profiling build with the fix?”
“Open app2-profiling.html in Chrome with DevTools, record in the Performance panel, and find the marks “downloaded”, “parsed” and “committed” in the Timings track.”
What usually goes wrong
Here JSON.parse took 17 ms out of a 1,897 ms frame. A faster parser would not be felt.
In the normal build onRender was called 0 times. Use development or react-dom/profiling.
✗ esbuild app.jsx --bundle --minify✓ esbuild app.jsx --bundle --minify --alias:react-dom/client=react-dom/profilingtoLocaleString with options builds a new formatter on every call: 532 ms for 10,000 totals.
✗ value.toLocaleString("en-IN", { style: "currency", currency: "INR" })✓ const money = new Intl.NumberFormat(...); money.format(value)The formatter fix helped, but style + layout still took about 1,279 ms. Measure again after every fix.
Development React does extra checks and is much slower. Measure speed in a production or profiling build.
Best practices
- Measure first; write down the slow step before changing code.
- Name your own steps with performance.mark - they also show in DevTools.
- Profile React with <Profiler> in a profiling build, not in development.
- Use long-animation-frame entries to separate script time from layout time.
- Test a suspect on its own before changing the app.
- Create formatters (Intl.NumberFormat, Intl.DateTimeFormat) once and reuse them.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Add performance.measure("parse", "downloaded", "parsed") and performance.measure("react", "parsed", "committed") to app2.jsx, and print every measure with performance.getEntriesByType("measure") in run2.mjs.
Show hintHide hint
A measure is an entry with name, startTime and duration - read entry.duration.
Change OrderRow to show order.items.map((it) => it.sku).join(", ") in a new cell. Use the Profiler and LoAF to find out which of the two costs - React or layout - grew more.
Profile a real page
Pick a slow page in one of your own React projects and produce a short report on where its time goes.
- Marks around your own data steps (download, parse, any transforms).
- A <Profiler> around the slowest part of the tree, in a profiling build.
- The longest animation frame, split into script and style + layout.
- One suspect tested on its own, and one fix measured before and after.
Key points
- At 10,000 orders JSON.parse took 17 ms - the obvious guess was wrong.
- The Profiler found a 642 ms render; one shared Intl.NumberFormat cut it to 195 ms.
- LoAF showed style + layout of about 1,279 ms that the formatter fix did not touch.
- The Profiler is silent in a normal production build - use react-dom/profiling.
- Measure, find, prove, fix one thing, measure again.
Quick check before you move on
Interview questions
How do you find out why a React page is slow?
Measure before changing anything: User Timing marks around data steps, the React Profiler (in development or a profiling build) for component render time, and the Performance panel or Long Animation Frames API to separate scripting from style/layout. Then fix the largest cost and measure again.
What does the Long Animation Frames API give you that the Long Tasks API does not?
Per-frame data including rendering: total and blocking duration, when style and layout started, and attribution for the scripts that ran (invoker, source, forced layout time) - so you can tell script cost from layout cost and see what caused it.
Why can a list that formats numbers or dates be slow, and how do you fix it?
Number.prototype.toLocaleString and Date.prototype.toLocaleString with locales/options create a new Intl formatter per call. Create one Intl.NumberFormat or Intl.DateTimeFormat outside the component and reuse it.
Quiz
- 1.
Why was toLocaleString so much slower than money.format?
- 2.
The formatter fix did not make the page fast. Why not?
- 3.
The top script in the long frame was MessagePort.onmessage. What does that tell you?
- 4.
Why test formatMoney() on its own in Node before changing the app?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...