Memory and performance in the browser
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
DocumentFragmentor build a string once. - Animate
transformandopacity, which the browser can do without layout. - Use
debouncefor input handlers andIntersectionObserverfor 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.