Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 156 · Under the Hood

JavaScript Performance

Make JavaScript faster - measure with performance.now and DevTools, pick better algorithms, batch DOM updates, avoid layout thrashing, lazy-load and use workers.

A fast page feels trustworthy; a slow one feels broken. Users notice when a button takes half a second to respond, when scrolling stutters, or when a page sits blank while megabytes of script download. Search engines notice too: Google's Core Web Vitals measure loading speed, responsiveness and visual stability.

The good news is that most JavaScript performance problems come from a small set of causes: doing work you don't need, doing it the slow way, touching the DOM too often, loading code too early, or blocking the main thread. In this lesson you'll learn to measure first, then fix each of those causes with techniques you can apply today.

Rule one: measure, don't guess

Developers are famously bad at guessing what's slow. A loop you worry about may take 0.1 ms, while an innocent-looking line that reads offsetHeight costs 30 ms. Always measure before and after a change.

performance.now() returns a high-resolution timestamp in milliseconds (with fractions), measured from when the page started. Subtract two of them to time a piece of code. For quick checks, console.time() and console.timeEnd() do the same with less typing (Debugging Techniques).

JS Measuring with performance.now()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A few habits make measurements trustworthy:

  • Warm up first. Engines compile hot code with an optimizing compiler after it runs a few times, so the first run is often slower.
  • Repeat and take the median, because other work on the computer adds noise.
  • Measure realistic data. A function that's instant on 10 items can crawl on 10,000.
  • Don't trust micro-benchmarks too much. Results vary between browsers and versions. Optimize what's slow in your app, not what a benchmark says is slow in theory.

For named timings that show up in DevTools, use performance.mark("start") and performance.measure("render", "start").

The DevTools Performance panel

For real pages, record a profile: open DevTools → Performance → click record, use the page, stop. You get a timeline showing every task on the main thread. Look for:

  • Long tasks (marked in red): any task over 50 ms blocks input and makes the page feel laggy.
  • Purple "Layout" and "Recalculate Style" blocks, especially many in a row — a sign of layout thrashing (below).
  • Bottom-Up and Call Tree tabs, which show which of your functions used the most time.

Chrome's Lighthouse tab gives an overall report with concrete suggestions, and the Core Web Vitals metric INP (Interaction to Next Paint) measures how quickly your page responds to clicks and taps.

Pick the right algorithm and data structure

The biggest wins rarely come from clever tricks. They come from doing less work. Searching an array with includes() checks every element; checking a Set with has() takes about the same time no matter how big it is. Inside a loop, that difference is enormous:

JS Array lookups vs Set lookups

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Other "do less work" wins: stop a loop early with find() or some() when you only need one match; cache results you compute repeatedly (memoization, see Functional Programming Patterns); and avoid re-sorting or re-filtering data that hasn't changed. Sets and Maps cover these collections in detail.

Batch DOM updates

JavaScript itself is fast. The DOM is where pages usually slow down, because changes can force the browser to recalculate styles, compute layout (sizes and positions) and repaint pixels.

Browsers are smart: they wait and apply many changes together before the next frame. You help them by building content off-page and inserting it once, instead of adding elements one by one to a live list (Creating Elements):

JavaScript
// Many separate insertions
for (const item of items) list.append(makeRow(item));

// One insertion: build in a fragment (or an array), then add once
const fragment = document.createDocumentFragment();
for (const item of items) fragment.append(makeRow(item));
list.append(fragment);

// Or replace everything in one call
list.replaceChildren(...items.map(makeRow));

Also prefer toggling a class over setting many inline styles one at a time (Styles and Classes), and use event delegation — one listener on a container instead of a thousand on its children.

Avoid layout thrashing

Some properties make the browser compute layout right now so it can give you an accurate answer: offsetWidth, offsetHeight, clientWidth, scrollTop, getBoundingClientRect(), getComputedStyle() and others. Reading one is fine. The trouble starts when you alternate reads and writes in a loop: every write invalidates the layout, and every following read forces a fresh, synchronous layout. That pattern is called layout thrashing (or forced synchronous layout).

The fix is simple: read everything first, then write everything.

Layout thrashing vs read-then-write

On most machines the interleaved version is many times slower, even though both do the same work. For animations, schedule DOM writes with requestAnimationFrame() so they happen right before the browser paints, and animate transform and opacity where possible — the browser can move those without recalculating layout.

Do less work, less often

Some events fire dozens of times per second: scroll, resize, pointermove, input. Running heavy code on every one wastes effort. Timers shows the two classic fixes:

  • Debounce: wait until the events stop for a moment, then run once (search-as-you-type).
  • Throttle: run at most once every N milliseconds (scroll position, drag).

Also use { passive: true } on scroll and touch listeners that never call preventDefault(). It tells the browser it can scroll immediately without waiting for your code.

Often you don't need scroll events at all. To react when something becomes visible — lazy images, infinite lists, "fade in" effects — use an IntersectionObserver, which the browser runs efficiently off the hot path.

Load less, and load it later

The fastest code is code the browser never downloads. A few techniques:

  • defer or type="module" scripts don't block HTML parsing (Adding JavaScript).
  • Native lazy loading delays offscreen images and iframes: <img src="chart.png" loading="lazy" alt="…">.
  • Dynamic import() loads a module only when it's needed, so a rarely used feature doesn't slow down every page load (Modules):
JavaScript
button.addEventListener("click", async () => {
  const { openEditor } = await import("./editor.js"); // downloaded on first click only
  openEditor();
});
  • Ship less code. Bundlers remove unused exports ("tree shaking") and minify the rest (Tooling). Check a package's size before installing it; a 70 KB date library to format one date is rarely worth it when Intl is built in.

Lazy loading in practice

Lazy loading means postponing work or downloads until the user is likely to need them. The benefits are concrete: a smaller first download and a faster first paint (which helps search ranking and bounce rates), less data used by visitors who never scroll down, and less memory spent on things nobody looks at.

Native loading="lazy" covers most images and iframes. When you need more control, use an IntersectionObserver: keep the real address in a data-src attribute and copy it into src when the element approaches the viewport.

Lazy-load an image with IntersectionObserver

Give lazy images explicit width and height so the page doesn't jump when they arrive, and never lazy-load the main image at the top of the page: that one should load first. Code can be lazy too: the dynamic import() above splits features into chunks fetched on demand. The cost is a short delay the first time, so load ahead of time on hover or when the browser is idle for features you expect the user to use.

Keep the main thread free

JavaScript in a page runs on the main thread, the same thread that handles clicks, typing and painting. While your code runs, nothing else can happen. A task that takes 300 ms freezes the page for 300 ms.

There are two ways out:

  1. Break long work into chunks and give the browser a chance to respond in between. await new Promise((r) => setTimeout(r, 0)) yields; the newer scheduler.yield() does it more efficiently in browsers that support it (feature-detect it, as below).
  2. Move the work off the main thread into a Web Worker: a separate thread with its own event loop. Workers can't touch the DOM, but they're perfect for parsing, image processing, search indexes and number crunching. You talk to them with postMessage().

Click Count primes below, then immediately try typing in the box. With the worker, the page stays responsive; on the main thread, it freezes until the work is done.

Main thread vs Web Worker

The demo builds the worker from a data: URL so it fits in one editor. In a real project, put the worker code in its own file. To send large binary data to a worker without copying it, transfer the buffer: worker.postMessage(buffer, [buffer]) (Typed Arrays and Binary Data).

Memory is performance too. Leaks make garbage collection run more often and longer, which shows up as random pauses. If a page gets slower the longer it's open, check for leaks first (Memory Management).

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What should you do before optimizing a piece of code?

    Intuition about speed is often wrong. Measure first, then measure again after the change to confirm it helped.
  2. 2. Why is reading offsetWidth right after changing a style, inside a loop, slow?

    A write invalidates layout, and the next layout read forces it to be recomputed immediately. Batch all reads before all writes.
  3. 3. You need to check 50,000 IDs against a list of 50,000 blocked IDs. What helps most?

    A Set lookup takes roughly constant time, while includes() scans the array. The data structure change beats any micro-optimization.
  4. 4. What is a Web Worker good for?

    Workers run in parallel with the main thread but can't access the DOM. They talk to the page with postMessage().
  5. 5. Which technique downloads a rarely used feature only when the user needs it?

    import() returns a promise and fetches the module on demand, keeping it out of the initial page load.

Summary

  • Measure first with performance.now(), console.time() and the DevTools Performance panel; warm up and take the median.
  • The biggest wins come from doing less work: better data structures (Set, Map), early exits and caching.
  • Batch DOM changes with fragments or replaceChildren(), and read layout values before writing styles.
  • Debounce or throttle busy events, use passive listeners, and prefer IntersectionObserver over scroll handlers.
  • Load less: defer/modules, loading="lazy", dynamic import() and smaller bundles.
  • Keep the main thread free by chunking long tasks or moving them into a Web Worker.

Next: JavaScript Versions and History — how the language grew from a 10-day prototype to yearly ECMAScript releases.