Skip to content

QuizNot attempted

Layout thrashing

Why is this slow?
for (const el of items) {
el.style.height = el.offsetHeight + 10 + 'px';
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Each offsetHeight read after a style write forces a synchronous layout (reflow): read and write alternate every iteration
  • Each offsetHeight read after a style write forces the browser to compute layout synchronously, so the loop alternates read/write and triggers a reflow every iteration (layout thrashing).
  • Batch reads, then writes (or write in requestAnimationFrame).
  • Not hardware acceleration: the cost is layout, not compositing.
  • Not string concatenation: trivially cheap.
  • Not for...of: loop overhead is negligible next to forced layouts.