What is the difference between DOM and Virtual DOM?

If you work on the front end of web apps, use JavaScript and modern frameworks, there is a good chance that you come across terms like DOM and Virtual DOM quite frequently. It is important to understand these underlying concepts to write better code and build efficient applications.

Now you may be wondering, why another article? There are so many already! You are right but the reason behind this is that while working on a project and going through resources online, I kept coming across this statement: “DOM is slow”. In this post, I want to clear things up.

What is DOM?

DOM – stands for Document Model Object. DOM is essentially a representation of a web page / document that allows us to interact with it. A more official definition is “an API (application programming interface) for documents”. DOM makes it possible for us to access web pages via scripting or programming languages. By using DOM (Web) APIs we can update, delete and create content and structure of a web document. You will see a lot of DOM diagrams online that show a hierarchical, tree-like representation of a document where the end of each branch is an HTML element. You can see how the diagram below resembles HTML markup structure.

There is a lot of confusion out there that DOM is slow. Let’s put it straight, DOM is not slow. When manipulating DOM directly browsers have to go through a number of steps (work out CSS, render layout, etc.) to display the page to us. And this happens on every change. Sure enough, the code can be optimised to make the process faster but this is out of scope for this short introductory article. So what else can be done?

What is Virtual DOM?

Let’s take React as an example. For those who are not too familiar with React, it is a library built by Facebook that it used for building complex user interfaces. For more info check the official React page.

When a change happens in a React component, it does not update the real DOM directly. Instead, React creates and holds a copy (a representation) of the real DOM in memory – the Virtual DOM (VDOM). Upon changes it compares the old DOM with the new Virtual DOM and updates only the necessary parts of the real DOM instead of the whole DOM. The diffing algorithms that React implements allows it to figure out what needs to be updated in the real DOM and optimize the steps so that the browser does not have to go through the same steps (parsing CSS, etc.) for every update.

We can see that the major benefit is the fact that the real DOM does not get updated as a whole, only the needed parts. React optimizes for better browser performance. It is also really cheap and quick to update the virtual DOM in terms of memory and time.

I hope that this clears up the myth that DOM is not slow. It’s how we interact with the DOM can make the browser processing time slower.