⚠️ This lesson is retired and might contain outdated information.

Solving layout thrashing by caching measured value

Yonatan Kra
InstructorYonatan Kra
Share this video with your friends

Social Share Links

Send Tweet

Layout thrashing is when we force the browser to measure the DOM multiple times during a synchronous process. This can have major performance consequences. In this lesson we will see the case in which measuring a static value from the DOM can cause layout thrashing - and it can be solved by caching the value.

Instructor: [0:01] We have an app that adds blue boxes to the screen. We can add a single box or 1,000 boxes. There's also a feature that allows us to compare the width of each child to the width of the parent wrapper. The function compareWidth iterates over the children of the wrapper and for each child, gets the width of the wrapper and sets it to the child.

[0:27] I'll refresh the screen and add three boxes. I'll trigger the comparison function and it works pretty fast. Let's test this with 1,000 entities. I add 1,000 blue boxes and start recording. I triggered the comparison and can already see there's a delay.

[0:47] Let's look at the results. First of all, we see the red line above our measurement which indicates a performance issue. We can also see the process took almost two seconds. Next, in the flame chart below, we can see the layout thrashing. A lot of layout reflows did repeat themselves.

[1:07] Let's look at the code to see how it happens. Layout reflow happens when we measured the dome after we mutate it in the same synchronous process. In this case, we mutate the dome and we measure it again in the second iteration. Then mutate it again and it goes on until the loop finishes.

[1:29] Because we measure a static property that does not change during the process, the solution in this case is caching the measured value. I'll copy the wrapper width measurement line to be outside the loop. Let's see the difference in the browser.

[1:44] I'll refresh the page and then the 1,000 boxes start recording and trigger the compareWidth function. It is visibly evident that our code run faster this time and there is no layout thrashing. We can also see it took much less time for the function to finish.

[2:02] To summarize, layout thrashing is the case of multiple reflows in the same synchronous process. In our case, it was the measurement of the wrappers width that was inside the loop that also changed the width of the element. We solve this by caching the measured value outside the loop.