CS Fundamentals Trainer · JavaScript · Performance & Memory
Why is this loop slow for 1,000 boxes, and what fixes it?
for (const box of boxes) {
box.style.width = box.parentElement.offsetWidth / 2 + 'px';
}
- `offsetWidth` makes the browser recompute styles for the entire document on every read; caching each value in `localStorage` avoids it.
- Building strings with `+ 'px'` allocates many temporary strings; switching to template literals removes the slowdown.
- Each style write triggers an immediate repaint; wrapping the loop body in `setTimeout(..., 0)` batches the paints together.
- Each style write invalidates layout, so the next `offsetWidth` read forces a synchronous layout; read all widths first, then write all styles.
Difficulty: medium