JavaScript Performance
Performance is how quickly your code does its job and how responsive the page stays while it does. In practice, most slow JavaScript isn't slow because the language is slow: it does too much work on the main thread, touches the DOM too often, downloads too much code, or uses the wrong data structure. The first rule of performance is measure first: find where time actually goes, fix that, and measure again. This lesson covers measuring, the biggest wins in browsers, debounce and throttle, and how to write code the engine can optimize.
In One Minute
- Measure before optimizing:
performance.now(), the DevTools Performance panel, Lighthouse. - Keep the main thread free: split long tasks, move heavy computation to Web Workers.
- Batch DOM work: read all layout values, then write; avoid alternating them (layout thrashing).
- Debounce fast events you only need at the end (typing); throttle ones you need regularly (scrolling).
- Load less: code splitting, lazy loading, smaller dependencies.
- Choose the right structure:
Set/Maplookups instead of repeated array searches; keep object shapes consistent.
Measure First
const payments = Array.from({ length: 50_000 }, (_, i) => ({ id: i, amount: i % 500 }));
const wanted = Array.from({ length: 2_000 }, (_, i) => i * 20);
let t = performance.now();
const slow = wanted.filter((id) => payments.some((p) => p.id === id));
const slowMs = performance.now() - t;
t = performance.now();
const ids = new Set(payments.map((p) => p.id));
const fast = wanted.filter((id) => ids.has(id));
const fastMs = performance.now() - t;
console.log(slow.length === fast.length, `Set version at least 10x faster: ${slowMs / fastMs > 10}`);true Set version at least 10x faster: trueExplanation: the first version searches the whole payments array for each wanted ID (2,000 × up to 50,000 comparisons); the second builds a Set once, then each lookup is instant. Exact times vary by machine, so the example prints only the comparison. In browsers, use the Performance panel to record what the page actually spends time on before changing anything.
| Tool | Shows |
|---|---|
performance.now(), performance.mark/measure | Precise timings in code |
| DevTools Performance panel | Every task, function call, layout and paint on a timeline |
| Lighthouse | Page-level scores and suggestions |
| Core Web Vitals (LCP, INP, CLS) | Real users' loading speed, responsiveness and layout stability |
Algorithms and Data Structures
The biggest wins usually come from doing less work, not from micro-tweaks:
| Slow pattern | Faster |
|---|---|
array.includes(x) / find inside a loop | Build a Set or Map once, then has/get |
| Sorting repeatedly | Sort once, or keep data sorted |
| Recomputing the same result | Memoize or cache it |
Building strings with += in huge loops | Collect in an array and join (modern engines handle += well for typical sizes) |
| Processing all data when you need a few items | Iterator helpers with take, find, or pagination |
JSON.parse(JSON.stringify(obj)) to copy | structuredClone, or copy only what changes |
Keep the Main Thread Free
Anything on the main thread blocks input and rendering. A task longer than about 50 ms feels sluggish; INP (Interaction to Next Paint) measures how long the page takes to respond to clicks and key presses.
| Technique | Use for |
|---|---|
Split work into chunks and yield (setTimeout, or scheduler.yield() where available) | Long loops over data |
| Web Workers | Heavy computation (parsing, reports, image processing) |
requestAnimationFrame | Visual updates, once per frame |
requestIdleCallback | Low-priority background work |
See "The Event Loop" for chunking and "Web Workers" for moving work off the main thread.
DOM Performance
Batch Reads and Writes
Reading a layout value (offsetHeight, getBoundingClientRect) after changing the DOM forces the browser to recalculate layout immediately. Alternating writes and reads in a loop causes layout thrashing:
<div id="list"></div>
<script>
const list = document.querySelector("#list");
for (let i = 0; i < 300; i++) {
const d = document.createElement("div");
d.textContent = `Row ${i}`;
list.append(d);
}
const rows = [...list.children];
let t = performance.now();
for (const row of rows) {
row.style.height = `${row.offsetHeight + 1}px`;
}
const thrash = performance.now() - t;
t = performance.now();
const heights = rows.map((row) => row.offsetHeight);
rows.forEach((row, i) => { row.style.height = `${heights[i] + 1}px`; });
const batched = performance.now() - t;
console.log("batched reads then writes was faster:", batched < thrash);
</script>batched reads then writes was faster: trueThe first loop forces 300 layout calculations (read, write, read, write...); the second reads everything first (one layout), then writes.
Other DOM Wins
| Do | Instead of |
|---|---|
Build elements, then insert once (append(...items), a fragment) | Inserting one at a time into the live page |
| Change a class | Setting many inline styles |
Animate transform and opacity | Animating width, top, margin |
| Event delegation (one listener) | A listener per row |
| Virtualize huge lists (render only visible rows) | Thousands of DOM nodes |
content-visibility: auto in CSS for long pages | Rendering off-screen sections |
Debounce and Throttle
Events like input, scroll, resize and pointermove fire many times per second. Handling each one can waste huge amounts of work.
- Debounce: wait until the events stop for a moment, then run once. Use for search-as-you-type, auto-save, resize handling.
- Throttle: run at most once per time interval while events keep coming. Use for scroll position, progress, drag.
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
function throttle(fn, ms) {
let last = -Infinity;
return (...args) => {
const now = performance.now();
if (now - last >= ms) {
last = now;
fn(...args);
}
};
}
const searches = [];
const search = debounce((term) => searches.push(term), 20);
for (const term of ["N", "Na", "Nav", "Navi", "Navika"]) search(term);
let handled = 0;
const onScroll = throttle(() => handled++, 25);
const start = performance.now();
while (performance.now() - start < 100) onScroll();
await new Promise((r) => setTimeout(r, 40));
console.log("debounced searches:", searches);
console.log("throttled: handled a handful of thousands of calls:", handled >= 3 && handled <= 6);debounced searches: ['Navika']
throttled: handled a handful of thousands of calls: trueFive keystrokes produced one search, for the final text; thousands of simulated scroll events produced about four handler runs in 100 ms. Production versions add options (run on the leading edge, cancel, flush), which libraries such as lodash provide.
Load Less Code
On most websites, the biggest performance cost is downloading, parsing and compiling JavaScript, especially on mid-range phones:
| Technique | Effect |
|---|---|
Code splitting with import() | Load features only when used |
defer or type="module" | Scripts don't block HTML parsing |
| Tree shaking and smaller libraries | Less code shipped |
| Compression (Brotli, gzip) and long-term caching (hashed file names) | Faster repeat visits |
loading="lazy" on images and iframes | Off-screen content loads later |
| Removing unused dependencies | Often the easiest big win |
Engine-Friendly Code
Modern engines optimize code that behaves predictably:
- Keep object shapes consistent. Create objects with the same properties in the same order (classes and factory functions do this naturally). V8 gives same-shaped objects the same hidden class, which makes property access fast.
- Don't add or delete properties after creation on hot objects; set all fields up front (to
nullif unknown). - Keep functions monomorphic: a function that always receives the same kinds of arguments is easier to optimize than one that receives numbers sometimes and strings other times.
- Keep arrays packed and uniform: no holes, one type of element.
class Payment {
constructor(name, amount) {
this.name = name;
this.amount = amount;
this.note = null;
}
}
const consistent = Array.from({ length: 3 }, (_, i) => new Payment(`P${i}`, i * 10));
console.log(consistent.every((p) => Object.keys(p).join() === "name,amount,note"));
const inconsistent = [{ name: "A", amount: 1 }, { amount: 2, name: "B" }, { name: "C" }];
console.log(new Set(inconsistent.map((p) => Object.keys(p).join())).size, "different shapes");true
3 different shapesThese are micro-optimizations: they matter in hot loops over large data, not in typical page code. Measure before contorting code for them.
In Practice
The Fee Tracker's student search applies three techniques: a precomputed lowercase index (computed once, not on every keystroke), a debounced input handler, and rendering at most 20 results:
<input id="q">
<ul id="results"></ul>
<script>
const names = Array.from({ length: 5000 }, (_, i) => ["Navika", "Srihitha", "Advitha"][i % 3] + " Anamaneni " + i);
const index = names.map((name) => ({ name, key: name.toLowerCase() }));
let searchesRun = 0;
function debounce(fn, ms) {
let t;
return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };
}
const render = debounce((term) => {
searchesRun++;
const q = term.trim().toLowerCase();
const matches = index.filter((r) => r.key.includes(q)).slice(0, 20);
const list = document.querySelector("#results");
list.replaceChildren(...matches.map((m) => Object.assign(document.createElement("li"), { textContent: m.name })));
console.log(`searches run: ${searchesRun}, rows shown: ${list.children.length}`);
}, 150);
document.querySelector("#q").addEventListener("input", (e) => render(e.target.value));
</script>searches run: 1, rows shown: 20Three changes to the search box produced one search, and the page never renders more than 20 rows.
Common Mistakes
Optimizing without measuring. You'll speed up code that didn't matter. Profile first.
Searching arrays inside loops. Build a Set or Map.
Interleaving DOM reads and writes. Batch reads, then writes.
Handling every scroll or input event. Debounce, throttle, or use observers.
Shipping too much JavaScript. Split, lazy-load and remove unused dependencies.
Under the Hood
V8 represents each object's layout with a hidden class (a map): a description of which properties exist and where each is stored. Objects created the same way share a map, and adding a property creates a transition to a new map. At each property access site, V8's inline cache remembers the maps it has seen and where the property was: with one map (monomorphic), access compiles to a single memory load; with a few (polymorphic), a short check; with many (megamorphic), a slow generic lookup. The optimizing compilers (Maglev, TurboFan) use this feedback to generate fast machine code and deoptimize when assumptions break. That is why consistent shapes and consistent argument types help hot code, and why delete on hot objects (which can turn them into slow dictionary-mode objects) hurts.
Practice
Challenge: Speed up findDuplicates(ids), which currently uses indexOf inside filter (quadratic time), by using a Set, and check that both versions agree on 20,000 IDs.
Show solution
const slow = (ids) => [...new Set(ids.filter((id, i) => ids.indexOf(id) !== i))];
function fast(ids) {
const seen = new Set();
const dupes = new Set();
for (const id of ids) (seen.has(id) ? dupes : seen).add(id);
return [...dupes];
}
const ids = Array.from({ length: 20_000 }, (_, i) => i % 15_000);
const a = slow(ids).toSorted((x, y) => x - y);
const b = fast(ids).toSorted((x, y) => x - y);
console.log(a.length, b.length, a.every((v, i) => v === b[i]));5000 5000 trueKey Takeaways
| Problem | Fix |
|---|---|
| Repeated searches | Set / Map lookups |
| Long tasks | Chunking, Web Workers |
| Layout thrashing | Read all, then write all |
| Fast-firing events | Debounce or throttle |
| Large bundles | Code splitting, lazy loading |
Was this tutorial helpful?