Part 01 · How the Browser Works
Latency Numbers for Frontend Engineers
A round trip on 4G, a disk-cache hit, a memory read and 50 ms of JavaScript side by side: the numbers every frontend decision is built on.
⏱ 6 min · Station 8 of 125
The problem
Two ShopLite engineers argue about the cart badge. One wants to read the cart from localStorage on every render "because it's slow". The other wants to call /api/cart on every page view "because it's always fresh". Both are guessing.
Every frontend decision (cache it or fetch it, compute it now or later, keep it in memory or in IndexedDB) is a bet on how long things take. Without the rough numbers in your head you can't tell a 30-nanosecond problem from a 600-millisecond one.
The idea
Frontend work happens at very different scales:
- Memory (a
Maplookup, a variable): nanoseconds. - Browser storage (
localStorage, IndexedDB): microseconds to sub-millisecond. - Main-thread work (parsing JSON, rendering a list): milliseconds, and it blocks everything else.
- Network: milliseconds on a good connection, hundreds of milliseconds per request on mobile.
The gaps between these levels are factors of 1,000 or more. Knowing which level an operation lives on tells you what's worth optimising, and what to keep off the critical path.
How it works
- Memory is close to free. A
Map.geton 10,000 products is a hash and a pointer: tens of nanoseconds, millions per frame. localStorageis synchronous. Reads come from an in-memory copy after the first access, so they're fast, but the API blocks the main thread, and the first read of a big value (or a write) can hit the disk.- IndexedDB is asynchronous. Each request goes through a transaction and another thread, so even a tiny read costs a few hundred microseconds, but it never blocks the main thread and it can hold far more data.
- JSON and the DOM cost main-thread time. Parsing a 446 KB API response or inserting 1,000 rows takes milliseconds, and it's milliseconds the user's clicks and frames wait for. On a 4x slower phone, multiply.
- The network is the long pole. A request to a local server takes a few milliseconds; on the slow 4G profile, about 600 ms, regardless of size for small responses. That's 36 frames.
- The HTTP cache cuts out the network, but not all of the cost: the browser still looks up the cache, reads the file and hands it to your code.
Rule of thumb: on a phone over mobile data, one avoidable request costs more than anything you'll do in memory all day.
On the slow 4G + 4x CPU profile, which is slower: parsing a 446 KB JSON string, or fetching 20 products from the API?
Visual
The ladder
| Operation | This laptop | Slow 4G + 4x CPU | If 1 ns were 1 s |
|---|---|---|---|
Map.get | 30 ns | 114 ns | 30 seconds |
localStorage.getItem | 640 ns | 1.8 µs | 11 minutes |
| IndexedDB get | 250 µs | 601 µs | 3 days |
JSON.parse 446 KB | 3.3 ms | 9.1 ms | 38 days |
| fetch from HTTP cache | 4.8 ms | 8.1 ms | 56 days |
| fetch from local server | 15.2 ms | 581.8 ms | 176 days / 18 years |
| one frame at 60 fps | 16.7 ms | 16.7 ms | 193 days |
| render 1,000 rows | 40.1 ms | 99.5 ms | 15 months |
(Human scale uses the laptop column, except the network row, which shows both.)
See it live
Measured on an Intel i3-10110U laptop (4 threads), 7 GB RAM, Ubuntu 26.04, Chrome 151 headless via Playwright 1.64.1, the lab in Docker on the same machine. Second column: the slow 4G profile (562.5 ms per request, 1.47 Mbps) and a 4x CPU slowdown, switched on after the page loaded.
latency.html runs each operation many times and reports the average for one. Tiny operations need many repeats because performance.now() is deliberately coarse in browsers (to blunt timing attacks):
<!doctype html>
<html>
<head><title>latency numbers</title></head>
<body>
<script>
// Each test runs many times and reports the average for ONE operation.
// performance.now() is rounded by the browser, so tiny things must be repeated to be measured.
const products = Array.from({ length: 10000 }, (_, i) => ({ id: i + 1, name: "Product " + (i + 1), price: i % 997 }));
const byId = new Map(products.map((p) => [p.id, p]));
const json = JSON.stringify(products); // 446 KB
localStorage.setItem("cart", JSON.stringify({ items: [{ productId: 7, qty: 2 }] }));
const avg = (n, fn) => {
const t = performance.now();
for (let i = 0; i < n; i++) fn(i);
return (performance.now() - t) / n;
};
const time = async (fn) => {
const t = performance.now();
await fn();
return performance.now() - t;
};
const idb = () =>
new Promise((ok) => {
const r = indexedDB.open("shop", 1);
r.onupgradeneeded = () => r.result.createObjectStore("cart");
r.onsuccess = () => {
const db = r.result;
const tx = db.transaction("cart", "readwrite");
tx.objectStore("cart").put({ productId: 7, qty: 2 }, "item7");
tx.oncomplete = () => ok(db);
};
});
const idbGet = (db) =>
new Promise((ok) => {
const q = db.transaction("cart").objectStore("cart").get("item7");
q.onsuccess = () => ok(q.result);
});
window.run = async (api) => {
let sink = 0;
const out = {};
out["Map.get (in memory)"] = avg(1_000_000, (i) => (sink += byId.get((i % 10000) + 1).price));
out["localStorage.getItem"] = avg(100_000, () => (sink += localStorage.getItem("cart").length));
out["JSON.parse 446 KB"] = avg(20, () => (sink += JSON.parse(json).length));
out["render 1,000 rows to DOM"] = await time(async () => {
const ul = document.createElement("ul");
for (const p of products.slice(0, 1000)) ul.insertAdjacentHTML("beforeend", `<li>${p.name} $${p.price}</li>`);
document.body.append(ul);
sink += document.body.offsetHeight; // force layout so the cost is real
ul.remove();
});
const db = await idb();
await idbGet(db);
let n = 0;
out["IndexedDB get"] = (await time(async () => { for (; n < 200; n++) await idbGet(db); })) / 200;
// Network: the first fetch goes to the server, the second comes from the HTTP cache.
const url = api + "/img/77.svg";
out["fetch over network (cold)"] = await time(() => fetch(url).then((r) => r.text()));
out["fetch again (HTTP cache)"] = await time(() => fetch(url).then((r) => r.text()));
out["fetch API, 20 products"] = await time(() => fetch(api + "/api/products?limit=20&n=" + Math.random()).then((r) => r.json()));
return { out, sink };
};
</script>
</body>
</html>
tools/latency.mjs runs the page twice, once as is and once throttled:
// node latency.mjs: how long common frontend operations take, measured in a real page.
// Runs twice: once on this machine as is, once with the "slow 4G + 4x CPU" profile.
import { open, WEB, API } from "./lib.mjs";
const fmt = (x) => (x < 0.001 ? `${(x * 1e6).toFixed(0)} ns` : x < 1 ? `${(x * 1000).toFixed(1)} us` : `${x.toFixed(1)} ms`);
const results = {};
for (const profile of ["none", "slow4g"]) {
const { browser, page, cdp } = await open();
await page.goto(`${WEB}/x/latency.html`, { waitUntil: "load" });
// throttle only after the page has loaded, so the page itself loads the same way both times
if (profile === "slow4g") {
await cdp.send("Network.emulateNetworkConditions", { offline: false, latency: 562.5, downloadThroughput: 188744, uploadThroughput: 86400 });
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });
}
results[profile] = (await page.evaluate((api) => window.run(api), API)).out;
await browser.close();
}
console.log("operation this laptop slow 4G + 4x CPU");
for (const k of Object.keys(results.none))
console.log(`${k.padEnd(31)} ${fmt(results.none[k]).padStart(11)} ${fmt(results.slow4g[k]).padStart(20)}`);
operation this laptop slow 4G + 4x CPU
Map.get (in memory) 30 ns 114 ns
localStorage.getItem 640 ns 1.8 us
JSON.parse 446 KB 3.3 ms 9.1 ms
render 1,000 rows to DOM 40.1 ms 99.5 ms
IndexedDB get 249.5 us 600.5 us
fetch over network (cold) 15.2 ms 581.8 ms
fetch again (HTTP cache) 4.8 ms 8.1 ms
fetch API, 20 products 9.4 ms 605.9 ms
Reading it:
- Memory and
localStorageare in the nanosecond range. Reading the cart fromlocalStorageon every render costs well under a microsecond. Engineer one's worry was misplaced, at least for a small value. - IndexedDB costs about 250 µs per read, 400x a
localStorageread, but asynchronously: fine for hundreds of items, not for a hot loop. JSON.parseof 446 KB: 3.3 ms, 9.1 ms throttled. Fine once; a problem if it runs on every keystroke.- Rendering 1,000 rows: 40 ms, 99.5 ms throttled. That's 2-6 frames of a blocked main thread from a single update. This is why lists get virtualised (Part 7).
- The network dominates the moment you throttle. 15 ms becomes 582 ms; 20 products from the API take 606 ms. Engineer two's "fetch on every page view" costs over half a second per view on mobile.
- The HTTP cache barely mattered on localhost (4.8 ms vs 15.2 ms, and single fetches are noisy), but on slow 4G it turned 582 ms into 8 ms. Caching is a mobile feature first.
In real apps
- Show the cached value first, then refresh. The cart badge reads from memory or
localStorageinstantly and updates when/api/cartanswers: stale-while-revalidate (Part 4). - Keep API responses small and few. Ask for the 20 products on screen, not all 10,000; combine calls the first screen needs.
- Big data goes to IndexedDB, small settings to
localStorage. Offline carts and message history live in IndexedDB (Part 9). - Heavy parsing and sorting move to a worker when they cross a few milliseconds on a slow device.
What goes wrong in production
- Optimising the wrong level: memoising a 30 ns lookup while the page makes 5 sequential requests.
- A large
localStoragevalue read at startup (a whole product catalogue as one JSON string): synchronous disk read plus a bigJSON.parse, on the main thread, before first paint. - Request waterfalls on mobile: each extra dependent request adds about 600 ms; on desktop Wi-Fi it adds 15 ms and nobody notices.
- Benchmarks on the developer laptop only: the right-hand column is closer to what most customers live with.
Key takeaway
Memory is nanoseconds, storage microseconds, main-thread work milliseconds, and mobile requests hundreds of milliseconds. Spend your effort on the level that dominates: usually fewer requests, then less main-thread work.
Practice
A ShopLite page needs the user's last 50 viewed products. Option A: keep them in localStorage as one JSON array (about 20 KB) and parse it on load. Option B: fetch them from /api/products?ids=... on load. Estimate both on the slow 4G + 4x CPU profile using the table, then decide.
Answer
Option A: a 20 KB JSON.parse is about 20 times smaller than the 446 KB measured above, so roughly 0.5 ms throttled, plus a localStorage read in microseconds (the first read of a big value can be slower, but still around a millisecond). Option B: one request, about 600 ms on slow 4G. A is over 100x faster and works offline. The trade-off: A can be stale or differ between devices, so a common design shows A immediately and syncs with the server in the background (B, off the critical path).
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →