Models, Objects, and Documents
Layers of the virtual
What is a virtual DOM? How can we understand what it is, what it does, and what advantages it can provide in rendering user interfaces?
One reason the notion of the DOM and the “Virtual DOM” can be confusing is that “DOM”, in both cases, actually refers to more than one thing.
The DOM is a model
It’s an object-oriented representation of an HTML document created by the browser. This in-memory representation is composed of nodes arranged in a tree structure. In a modern web app, the term “document” encompasses everything you see and interact with in the browser window: the user interface. So the DOM is an in-memory representation of a web app’s user interface.
The DOM is an API
It’s also an interface between your code and the document itself. The Document object exposes methods for interacting with the document. This is what makes a document dynamic rather than static.
Is the DOM slow?
This question immediately becomes, “relative to what?” Traversal and manipulation of the DOM tree is not always the slowest part of updating a view: as the complexity of a web app increases, DOM manipulation is only part of the challenge and it’s not always the performance bottleneck. Adding, removing and changing DOM nodes is comparable to other manipulations of JavaScript objects. And modern JavaScript engines are fast. What is actually slow are operations the browser must perform to continually present us with an updated version of the view. When a web page UI changes, the browser engine has to recalculate CSS, re-flow the layout of the view, and re-paint the screen. The DOM is only a part of this process.
What actually happens when we manipulate the DOM, such as replacing an element on a page? A brief (incomplete) overview of what the browser does looks like this:
document.querySelector('#elementId').appendChild(newNode)
- Re-parse the HTML
- Update the DOM with the new appended node
- Re-calculate the CSS for the parent and child nodes
- Update the layout coordinates of each element on the screen
- Reflow the layout structure of the updated element and all child & ancestor elements (reflows are expensive)
- Re-paint the display, verifying visibility of all nodes
“Reflows are very expensive in terms of performance, and is one of the main causes of slow DOM scripts, especially on devices with low processing power, such as phones. In many cases, they are equivalent to laying out the entire page again” (Stubbornella)
Get Anthony Fields’s stories in your inbox
Join Medium for free to get updates from this writer.
It turns out that the 6 steps above (and more) will be carried out for every single change to the DOM. Append three nodes and this process will repeat three times. The virtual DOM introduces a layer of abstraction that mitigates this issue.
Statefulness
Components of the (non-virtual) DOM have an internal state — a <select> element having a default value, for example. With respect to the virtual DOM, think of state more generally as simply a value that has the potential to change. Interaction with the UI changes state. State is preserved (and overwritten) as the contents of a location in memory. When state changes, we need to track the change: this is done with a pair of previous state and new state. For example, a checkbox with a previous state of unchecked and new state of checked. Or a button that changes a value or emits an event. In the end, the statefulness of the non-virtual (“real”) DOM is a key reason why virtualizing it increases efficiency. More on why this is the case below.
When a web application is highly interactive and must respond in “real-time”, states are changing in such a way that the demand on the browser engine to re-flow and re-paint the screen can reach a point where the engine may not maintain an update rate of 60 frames per second, which results in a perceived lag or slow-down of the UI. Browser makers are always working on increasing the efficiency of updates. One way to do this is to minimize and batch together the changes that need to be carried out as outlined in the 6 points above.
While browsers do this minimizing and batching on a lower level, the virtual DOM is an abstraction of this same idea on a higher level. In this way the virtual DOM can mitigate performance bottlenecks as well. And the term “virtual DOM”, like “DOM”, also refers to more than one thing. So let’s unpack it’s meaning a little.
The virtual DOM is a JavaScript object
The virtual DOM is a JS object, much lighter “weight” than the browser’s Document object. It can be repeatedly re-created with very low overhead in performance terms. And it is re-created, as a pair. To return to the distinction between previous state and new state — this distinction is reflected in the entire virtual DOM object residing in memory. There always exist two virtual DOM objects: one expresses the previous state and one the new state. These two object states are compared by the virtual DOM engine …
The virtual DOM is an algorithm
The virtual DOM object is coupled with an engine that implements an efficient algorithm. The algorithm is a procedure that reconstructs the entire object for each change in state, then scans it to identify the changes. Then, it performs a diff between the previous object state (as a whole) and the new object state: it computes the difference between the two states to obtain a result that it applies as a batch of changes to the DOM (in React, this diff step is a carefully constructed approximation algorithm that runs in O(n), if you’re curious). This result is intended to be the minimum number of changes required to perform an update. The algorithm actually produces something like an approximate minimum:
Breadth First Search
Since the virtual DOM object is lightweight, when updates to a parent component are required, all of it’s child components will be re-created as well. This means there’s no need to descend to each node in the tree whose state has changed, only to the first new-state node at a given level. Consequently, breadth-first search can be used when performing a comparison of the two virtual DOM objects. This is part of how the minimum number of changes is computed and batched. If node B and E below have changed state, when B is reached, its entire subtree will be re-created, regardless of any state changes below it. There’s no reason to traverse past B in the virtual DOM tree.
So maybe the DOM as such isn’t so slow … but in taking the entire process of udpating a view into account, it starts to become apparent that the virtual DOM can increase efficiency. On top of efficiency, there’s also the gains in developer productivity and happiness to be considered. If you’re working directly on the browser DOM, especially for complex web apps, the most difficult and error-prone task is manipulating that DOM. The virtual DOM approach abstracts away that imperative-driven task and lets us focus on building out applications declaratively using components. It also removes state management from the DOM itself, which is a very significant achievement on its own. Perhaps a good way to really dive into the subject of virtual DOMs is to work toward a deep understanding of state in React.










