Open In App

Explain DOM Diffing

Improve
Improve
Like Article
Like
Save
Share
Report

DOM Diffing or Document Object Model Diffing is the concept of comparing the DOMs before and after the modification and ensuring efficient updates. Before understanding DOM Diffing deeply, we should know what DOM is and what is its purpose.

Prerequisites:

What is a DOM ? :

In a formal sense, a DOM is an application programming interface (API) for documents. DOM defines a logical structure for a document and helps developers to access and manipulate a document. It very closely resembles the document models. For example, consider the following HTML list.

<ul>
<li></li>
<li></li>
<ol>
<li></li>
<li></li>
</ol>
</ul>

The DOM represents the list as follows:

DOM representation of the HTML list

As we can see, a DOM is very much like a tree.

Now let’s understand the concept o Virtual DOM.

Let’s start the answer with why. Every time there is a change in the UI of our application, the DOM updates, which means the whole tree is updated, and then the UI components are rerendered. This rerendering of UI elements every time a small change makes an application slow, and hence, the denser your UI is, the slower our DOM updates will be. And this is where a Virtual DOM comes into the picture. A Virtual DOM is a virtual representation of a Real DOM discussed above. Now when there is a state change in the UI of our application, only the virtual DOM is updated instead of the real DOM. The next thing to ask is how updating virtual DOM improves performance. 

DOM Diffing :

Whenever there is a change in the state of the UI elements, a new virtual DOM is created. Then the new virtual DOM and the previous virtual DOM are compared with each other. This comparing is called DOM diffing.

The intention is to perform minimal operations on the real DOM, hence after diffing, the best way to update the real DOM is calculated, leading to an efficient update of the UI.

The following image shows the diffing process:

DOM Diffing

The image shows that the update on the real DOM is postponed as further as possible. The red node represents state change; then, the changes are calculated through DOM diffing, and finally, the new virtual DOM is batch updated to the real DOM.

Conclusion:

Updating UI is very expensive; updating the real DOM in batches improves the overall performance of repainting the UI.


Last Updated : 10 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads