Skip to content
Velloreth
Programming 7 min read

JavaScript Performance: Practical Optimisation Tips

Most JavaScript is fast enough. Learn where the real bottlenecks are, how to measure, and the optimisations that actually matter.

By

Measure first

The first rule of performance work: measure.

console.time('operation');
doWork();
console.timeEnd('operation');

For a real profile, use the Performance panel:

  1. Open DevTools and go to Performance.
  2. Click Record.
  3. Perform the slow interaction.
  4. Stop and inspect the flame graph.

Look for:

  • Long tasks — anything over 50ms, marked in red.
  • Repeated functions — a function appearing many times in the flame graph.
  • Layout and paint — purple and green blocks, which indicate rendering work.
  • Gaps — idle time, which means the bottleneck is elsewhere.

Intuition about performance is usually wrong. The bottleneck is rarely where you expect.

The main thread

JavaScript runs on the main thread, which also handles rendering and input. A long task blocks everything.

The 50ms budget. A task over 50ms is a “long task” and can cause visible jank. Interaction to Next Paint (INP) measures this from the user’s perspective.

Break up long tasks. Yield to the browser periodically.

async function processLarge(items) {
  for (let i = 0; i < items.length; i++) {
    process(items[i]);
    if (i % 100 === 0) {
      await new Promise((r) => setTimeout(r, 0)); // yield
    }
  }
}

Move work off the main thread. A Web Worker runs in a separate thread.

// worker.js
self.onmessage = (e) => {
  const result = heavyComputation(e.data);
  self.postMessage(result);
};

// main.js
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = (e) => console.log(e.data);

Workers are the right answer for CPU-intensive tasks: parsing large files, image processing, complex calculations, and cryptography.

Reduce work

The most effective optimisation is doing less.

Avoid unnecessary computation. Cache results that do not change.

// Recomputes on every render
const total = items.reduce((sum, i) => sum + i.price, 0);

// Computed once
const total = useMemo(() => items.reduce((sum, i) => sum + i.price, 0), [items]);

Use the right data structure. A Set lookup is O(1); an array scan is O(n).

// O(n) per check
if (allowedIds.includes(id)) { }

// O(1) per check
const allowedSet = new Set(allowedIds);
if (allowedSet.has(id)) { }

Short-circuit early. Return as soon as the answer is known.

// Processes everything
const hasError = logs.filter((l) => l.level === 'error').length > 0;

// Stops at the first
const hasError = logs.some((l) => l.level === 'error');

Avoid repeated DOM queries.

// Queries the DOM on every iteration
for (let i = 0; i < 100; i++) {
  document.querySelector('.item').classList.add('active');
}

// Queries once
const item = document.querySelector('.item');
for (let i = 0; i < 100; i++) {
  item.classList.add('active');
}

Reduce allocations

Allocation triggers garbage collection, which pauses execution.

Avoid creating objects in hot loops.

// Allocates a new object per iteration
items.map((i) => ({ ...i, processed: true }));

// Mutates in place when safe
for (const item of items) item.processed = true;

Reuse arrays and objects where the API allows.

Avoid string concatenation in a loop for large strings; use an array and join.

// Repeated reallocation
let html = '';
for (const item of items) html += `<li>${item}</li>`;

// One allocation
const html = items.map((item) => `<li>${item}</li>`).join('');

DOM operations

DOM operations are expensive because they can trigger layout and paint.

Batch DOM writes. Read all values first, then write.

// Layout thrashing: read, write, read, write
for (const el of elements) {
  const height = el.offsetHeight; // read (forces layout)
  el.style.height = height + 10 + 'px'; // write (invalidates layout)
}

// Batched: read all, then write all
const heights = elements.map((el) => el.offsetHeight);
elements.forEach((el, i) => {
  el.style.height = heights[i] + 10 + 'px';
});

Use a DocumentFragment to build a subtree off-document.

const fragment = document.createDocumentFragment();
for (const item of items) {
  const li = document.createElement('li');
  li.textContent = item;
  fragment.appendChild(li);
}
list.appendChild(fragment); // one reflow

Use CSS classes, not inline styles, for repeated changes.

Animate transform and opacity, which are composited.

Event handling

Debounce waits until events stop.

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

input.addEventListener('input', debounce(search, 300));

Use for search input, form validation, and autosave.

Throttle runs at most once per interval.

function throttle(fn, limit) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= limit) {
      last = now;
      fn(...args);
    }
  };
}

window.addEventListener('scroll', throttle(onScroll, 100));

Use for scroll, resize, and mousemove.

Use passive listeners for scroll and touch, so the browser does not wait for the handler.

window.addEventListener('scroll', onScroll, { passive: true });

Use requestAnimationFrame for visual updates, so they align with the frame.

function animate() {
  updatePosition();
  requestAnimationFrame(animate);
}

Remove listeners when they are no longer needed, to avoid leaks.

Loading and parsing

Code splitting. Load only what the current route needs.

const module = await import('./heavy-module.js');

Defer non-critical scripts.

<script src="app.js" defer></script>

Avoid large dependencies for small tasks. A date library for one format call is not worth 20KB.

Tree shake. Use named imports and avoid namespace imports.

What does not matter

Micro-optimisations. Avoiding a closure, using for instead of forEach, caching array.length — these save nanoseconds and are invisible next to a single DOM operation.

Premature optimisation. Optimising code that is not slow adds complexity for no benefit.

Benchmarking in isolation. A microbenchmark that shows one loop is 5% faster than another tells you nothing about your application.

The rule: optimise what the profiler shows is slow, and leave the rest readable.

Memory and leaks

A memory leak makes a page slower over time and eventually crashes the tab.

Common causes:

Event listeners not removed. A listener holds a reference to its closure, which holds everything the closure references.

// Leak: the listener keeps the component alive
element.addEventListener('click', handler);

// Cleanup
element.removeEventListener('click', handler);

Timers not cleared. A setInterval that is never cleared keeps running and holds its closure.

const id = setInterval(tick, 1000);
clearInterval(id); // when done

Detached DOM nodes. A removed element that is still referenced by a variable is not collected.

let cached = document.querySelector('.panel');
cached.remove(); // still referenced by `cached`
cached = null;   // now collectable

Growing caches. An unbounded cache grows forever. Cap it and evict.

if (cache.size > 100) {
  cache.delete(cache.keys().next().value);
}

Closures capturing large objects. A small callback that closes over a large array keeps the array alive.

Finding leaks. Use the Memory panel: take a heap snapshot, interact with the page, take another, and compare. Look for objects that should have been collected.

Measuring in the field

Lab measurements use a fast machine and a good connection. Real users do not.

Use the Web Vitals library to report real-user metrics.

import { onCLS, onINP, onLCP } from 'web-vitals';

onCLS(console.log);
onINP(console.log);
onLCP(console.log);

Watch the percentiles. The median is fine; the 75th and 95th percentiles are where the problems are. A page that is fast for most users and slow for a tenth is still a problem.

Segment by device and connection. A slow phone on a 3G connection has a very different experience from a laptop on fibre.

Test on a throttled connection. DevTools can simulate slow networks and CPUs, which surfaces problems that a fast machine hides.

Practical guidance

  • Measure with the Performance panel before changing anything.
  • Keep tasks under 50ms and yield in long loops.
  • Use a Web Worker for CPU-intensive work.
  • Reduce work — cache, short-circuit, use the right data structure.
  • Batch DOM reads and writes to avoid layout thrashing.
  • Debounce and throttle high-frequency events.
  • Use passive listeners for scroll and touch.
  • Skip micro-optimisations — they rarely matter.

For the related guides, see javascript-debugging-console and javascript-array-methods-guide. For the broader context, improve-inp-core-web-vitals-static-site and how-cdns-actually-work.

Quotable summary

Measure before optimising, because intuition about performance is usually wrong and the bottleneck is rarely where you expect. The main thread is the constraint, so long tasks over 50 milliseconds block interaction and cause jank, which is why CPU-intensive work belongs in a Web Worker. Reduce work first, then allocations, then the frequency of expensive operations, and use the right data structure — a Set lookup is O(1) where an array scan is O(n). Batch DOM reads and writes to avoid layout thrashing, debounce and throttle high-frequency events, and use passive listeners for scroll and touch. Micro-optimisations like avoiding closures rarely matter; algorithmic improvements and fewer DOM operations usually do.

Frequently asked questions

How do I find a JavaScript performance problem?
Use the Performance panel in DevTools to record a profile and inspect the flame graph. Look for long tasks, functions that appear repeatedly, and layout thrashing. Measure before changing anything.
What is a long task?
A task that takes more than 50 milliseconds on the main thread. Long tasks block the browser from responding to input, which makes the page feel frozen. Break them up or move them off the main thread.
What is the difference between debounce and throttle?
Debounce waits until the events stop before running, which suits search input. Throttle runs at most once per interval, which suits scroll and resize handlers.
What is layout thrashing?
It is alternating reads and writes of layout properties, which forces the browser to recalculate layout repeatedly. Batch all reads, then all writes, to avoid it.
Should I use a Web Worker?
Yes, for CPU-intensive work that does not need DOM access, such as parsing large files, image processing, or complex calculations. It moves the work off the main thread so the UI stays responsive.
Are micro-optimisations worth it?
Rarely. Avoiding a closure or using a for loop instead of forEach saves nanoseconds. Algorithmic improvements, fewer DOM operations, and less work overall save milliseconds or seconds.