Kayavak

Kayavak / Work backwards

Work backwards

The same loop, 30 times slower in a different order

Widening 500 boxes by a pixel took 54.9 ms one way and 1.9 ms another, with exactly the same reads and writes.

The result

Volume 2's DOM lab widened 500 boxes by one pixel each: read a box's width, set it one pixel wider. Doing read, write, read, write… took 54.9 ms. Doing all the reads, then all the writes, took 1.9 ms (the lab).

Same reads, same writes, same results.

Work back from it

First question: what does the browser have to know to answer `offsetWidth`?

The element's current geometry, which comes from layout: the browser's computation of every box's size and position (layout).

Step 1: what does setting `style.width` do to that geometry?

It invalidates layout: the stored positions may now be wrong. The browser doesn't recompute straight away; it marks layout dirty and normally recomputes once, before the next frame is drawn (layout invalidation).

Step 2: so what happens on the next loop iteration's read?

The page asks for a width while layout is dirty, so the browser must recompute layout immediately to answer: a forced synchronous layout. Interleaved, that's 500 layouts. Batched, the reads all happen before anything is dirty and the writes all happen after, so layout runs once.

The root cause

Reading geometry after a write forces the browser to lay the page out again, there and then. In a loop that's layout thrashing (forced synchronous layout).

What follows from it

Recall

Why does read-write-read-write force many layouts?

Each write makes layout dirty, and each geometry read then forces the browser to recompute layout immediately.

How do you avoid it?

Do all the reads first, then all the writes (or read in requestAnimationFrame and write after).