🟒 EasyPerformanceπŸ“– Theory Question

What is the difference between reflow and repaint, and how do you avoid layout thrashing?

πŸ’‘

Hint

Reflow=recalculate layout (expensive cascade); repaint=visual update only; batch DOM reads/writes

Full Answer

Repaint β€” visual property change (color, background, visibility) without affecting layout. Less expensive.

Reflow (Layout) β€” geometry change (width, height, position, padding, margin). Expensive: cascades through the document.

// Layout thrashing β€” alternating reads and writes force reflow each iteration
for (let i = 0; i < 100; i++) {
  const h = el.offsetHeight;       // READ β€” forces layout (reflow)
  el.style.height = h + 1 + 'px'; // WRITE β€” invalidates layout
}
// Browser must reflow 100 times! ❌

// Fix: batch all reads, then all writes
const h = el.offsetHeight; // single read
for (let i = 0; i < 100; i++) {
  el.style.height = (h + i) + 'px'; // writes only
}

// Best fix: CSS transforms β€” composited on GPU, NO reflow
el.style.transform = 'translateY(10px)'; // skip layout entirely!

// Properties that DON'T trigger reflow (GPU composited):
// transform, opacity, filter, will-change

What triggers reflow: offsetWidth/Height, getBoundingClientRect(), scrollTop, getComputedStyle(), adding/removing DOM nodes, font changes.

πŸ’‘ Use requestAnimationFrame to batch DOM reads and writes in the correct phase. Libraries like FastDOM enforce this pattern.

More Performance Questions

🟒 EasyWhat are debounce and throttle? When do you use each?β†’πŸŸ’ EasyWhat causes memory leaks in JavaScript and how do you detect them?β†’πŸŸ‘ MediumWhat is lazy loading and code splitting?β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint