JavaScript Performance

Updated · 10 min read
mediumES2026javascriptperformancedebouncethrottleoptimization

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/Map lookups instead of repeated array searches; keep object shapes consistent.

Measure First

measure.js▶ Try it
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}`);
Output
true Set version at least 10x faster: true

Explanation: 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.

ToolShows
performance.now(), performance.mark/measurePrecise timings in code
DevTools Performance panelEvery task, function call, layout and paint on a timeline
LighthousePage-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 patternFaster
array.includes(x) / find inside a loopBuild a Set or Map once, then has/get
Sorting repeatedlySort once, or keep data sorted
Recomputing the same resultMemoize or cache it
Building strings with += in huge loopsCollect in an array and join (modern engines handle += well for typical sizes)
Processing all data when you need a few itemsIterator helpers with take, find, or pagination
JSON.parse(JSON.stringify(obj)) to copystructuredClone, 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.

TechniqueUse for
Split work into chunks and yield (setTimeout, or scheduler.yield() where available)Long loops over data
Web WorkersHeavy computation (parsing, reports, image processing)
requestAnimationFrameVisual updates, once per frame
requestIdleCallbackLow-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:

thrashing.html
<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>
Output
batched reads then writes was faster: true

The first loop forces 300 layout calculations (read, write, read, write...); the second reads everything first (one layout), then writes.

Other DOM Wins

DoInstead of
Build elements, then insert once (append(...items), a fragment)Inserting one at a time into the live page
Change a classSetting many inline styles
Animate transform and opacityAnimating 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 pagesRendering 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.
debounce-throttle.js▶ Try it
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);
Output
debounced searches: ['Navika']
throttled: handled a handful of thousands of calls: true

Five 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:

TechniqueEffect
Code splitting with import()Load features only when used
defer or type="module"Scripts don't block HTML parsing
Tree shaking and smaller librariesLess code shipped
Compression (Brotli, gzip) and long-term caching (hashed file names)Faster repeat visits
loading="lazy" on images and iframesOff-screen content loads later
Removing unused dependenciesOften 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 null if 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.
shapes.js▶ Try it
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");
Output
true
3 different shapes

These 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:

search.html
<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>
Output
searches run: 1, rows shown: 20

Three 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
duplicates.js▶ Try it
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]));
Output
5000 5000 true

Quick check: Performance

3 questions
1What is the first step when code feels slow?
2Which technique fits a search box that queries a server as the user types?
3What causes layout thrashing?

Key Takeaways

ProblemFix
Repeated searchesSet / Map lookups
Long tasksChunking, Web Workers
Layout thrashingRead all, then write all
Fast-firing eventsDebounce or throttle
Large bundlesCode splitting, lazy loading

Was this tutorial helpful?

Lesson 126 of 139