appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Memory and performance in the browser

Lesson 3 of 411 minAdvanced

Find leaks, avoid layout thrashing and measure what users feel.

JavaScript frees memory automatically with garbage collection: objects that nothing can reach are removed. A leak is memory that is still reachable but no longer needed.

  • Event listeners that are never removed and keep large objects alive.
  • Timers (setInterval) that are never cleared.
  • Global variables and caches that grow without limit.
  • Detached DOM nodes still referenced by your code.

In the browser DevTools, the Memory tab takes heap snapshots. Take one, use the app, take another and compare. Steady growth after you repeat an action means a leak.

Rendering cost

// Bad: reading layout and writing styles alternately forces many reflows
for (const el of items) {
  el.style.width = el.parentNode.offsetWidth / 2 + "px";
}
// Better: read everything first, then write
const widths = items.map((el) => el.parentNode.offsetWidth);
items.forEach((el, i) => { el.style.width = widths[i] / 2 + "px"; });
  • Batch DOM changes, and use DocumentFragment or build a string once.
  • Animate transform and opacity, which the browser can do without layout.
  • Use debounce for input handlers and IntersectionObserver for lazy loading.
  • Ship less JavaScript: split code and load it only when needed (import()).

Measure what users feel

The Core Web Vitals are LCP (loading, aim under 2.5 s), INP (responsiveness, under 200 ms) and CLS (visual stability, under 0.1). Measure with Lighthouse and with real user data, and fix the worst first.

Noteperformance.mark() and performance.measure() let you time your own code and see it in the DevTools Performance panel.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What is a memory leak in a garbage-collected language?
2. Which CSS properties are cheapest to animate?
3. What does INP measure?

Key terms