Blog
Learning material for professionals eager to explore the science behind building a successful online product

#ASKTHEINDUSTRY 10: Is the DOM really slow? Can we work around it?

“The DOM is slow” they say. A lot of us have challenged this notion and put up several benchmarks that show how fast DOM operations can be. However, it is indeed true that, most of the times, bad runtime performance is associated with (and apparently caused by) one or many DOM modifications. So what’s wrong here?

Let me tell you this first: the DOM is not slow. Adding and removing a DOM node is (at least theoretically speaking) just a matter of swapping pointers. To be honest, it isn’t any different from setting a property on an object.

Whenever our JavaScript code touches the DOM, a dirty bit is set on the tree

The missing piece of the puzzle is called layout. Unless we’re being really careful, touching the DOM will trigger the full rendering pipeline: styles calculation, layout, paint and compositing. Basically, whenever our JavaScript code touches the DOM, a dirty bit is set on the tree; then, as soon as the browser gets control back, it needs to figure out what changed, possibly recomputing where things are supposed to be (re)painted. There is not a lot we can do to limit the scope of this expensive process, a part from a couple of pretty useful CSS primitives.

Don’t give up hope, though!

For all these reasons, some really smart people came up with a great idea: the Virtual DOM. Basically, it is a smaller and simpler representation of the DOM that lives in memory and is completely detached from the actual tree. This way, you can modify the vDOM without the browser noticing.

One library that I love using for this is diffhtml. It feels great, when paired with the new ES2015 template literals, and it allows you to play with the Virtual DOM as you normally would with the actual DOM. Then, diffhtml will figure out how to modify the page with the minimum amount of operations, and execute them all in batch, avoiding layout thrashing on your behalf.

The results are stunningly fast. Big DOM trees are a problem of the past.

This piece is part of the #ASKTHEINDUSTRY project, a series of daily conversations with the Web Dev industry. You ask, I’ll answer, or find someone who can.

Care to leave a comment? Drop down a line on the Twitters