yash
yash

Reputation: 85

How exactly Virtual DOM is faster than real DOM?

I know VDOM is just representation of real DOM which diffs with previous VDOM when some nodes have changed. But after all it is real DOM which going to take this output and repaint and redraw the screen, which is said to be dumb that it does not know how to change only the part of screen. I want to know how browser or real DOM differentiates that now I am dealing with VDOM and now with some regular stuff.

Upvotes: 2

Views: 2020

Answers (1)

I want to know how browser or real DOM differentiates that now I am dealing with VDOM and now with some regular stuff.

The browser knows that you are doing some DOM stuff when you actually call methods on DOM objects (Node, Element, etc.).

DOM objects are totally separate from, and ignorant of, any Virtual DOM you might have in your code. Virtual DOM is really just a graph of regular JavaScript objects. There is nothing special at all about these objects. The fact that they supposedly represent part of a DOM document is known to us, but the browser couldn't care less; to it, it's just objects.

Diffing two Virtual DOM instances means finding the difference(s) in two object graphs. Again, from the browser's (or, more generally, the JavaScript execution environment's) perspective it's no different than diffing any other two JavaScript objects.

The resulting diff needs to be translated into DOM API calls. That is when the browser will realise that you're doing something to the DOM which might require reflowing & repainting the document on-screen.

How exactly Virtual DOM is faster than real DOM?

Virtual DOM per se does not have any speed. It's not slower, nor faster, than the DOM. It's simply an object. Modifying a Virtual DOM object graph is supposedly faster than modifying DOM objects because it will not immediately & automatically trigger reflow & repaints, so you can use the Virtual DOM as a "staging area" where you can prepare some future state of the DOM. Then when you're ready, use diffing to find the smallest number of changes that need to be applied to the DOM for the whole batch of changes you've made to the Virtual DOM since the last time.

(PS: If you're looking for raw speed, Virtual DOM as used in current frameworks (React, Vue.js, etc.) isn't your fastest option. See Rich Harris' talk at YGLF, "Rethinking reactivity" if you're curious.)

Upvotes: 7

Related Questions