Saturday, December 28, 2024
Google search engine
HomeLanguagesExplain DOM Diffing

Explain DOM Diffing

Before understanding what DOM Diffing is, we should know what DOM is and what is its purpose. In this article, we will learn about the two versions of DOM, the Real and the Virtual, and then we will cover what DOM diffing is.

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 help developers to access and manipulate a document. It very closely resembles the document models. For example, consider the following HTML list.

HTML




<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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments