TypeScript

JavaScript Tips for Performance

I've spent years profiling JavaScript applications. Most performance problems come down to the same handful of mistakes. Here are the ones I see most often.

14 Oct 2023

JavaScript Tips for Performance

I've spent years profiling JavaScript applications. Most performance problems come down to the same handful of mistakes. Here are the ones I see most often.

Avoid unnecessary loops

The issue isn't that loops are slow. It's that people do too much inside them.

Move invariant calculations outside the loop. If you're computing the same value on every iteration, compute it once before the loop starts. The less work per iteration, the faster it runs.

Minimize DOM access

Every time you touch the DOM, the browser has to do work. Read a property? It might trigger a layout recalculation. Write a property? It queues a repaint.

Batch your DOM reads together, then batch your writes together. Don't interleave them. Reading, writing, reading, writing forces the browser to recalculate layout on every cycle.

Cache repeated lookups

If you access the same object property or DOM element multiple times, store it in a variable:

Javascript
// Slow — traverses the DOM on every iteration
for (let i = 0; i < document.querySelectorAll('.item').length; i++) {
  // ...
}

// Fast — one DOM query, result cached
const items = document.querySelectorAll('.item');
const len = items.length;
for (let i = 0; i < len; i++) {
  // ...
}

Debounce expensive event handlers

Scroll, resize, and input events can fire dozens of times per second. If your handler does heavy work (DOM updates, API calls), debounce it:

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

window.addEventListener('scroll', debounce(handleScroll, 100));

The real lesson

Most performance work isn't about clever tricks. It's about measuring first, then fixing what actually matters.

Use browser DevTools Performance tab. Profile before you optimize. The bottleneck is almost never where you think it is.

Premature optimization wastes time. Targeted optimization based on measurements saves users real seconds.