How Virtual DOM is Powering React Performance?
I have heard about React for a long time. The overwhelming number of tutorials on React made my learning very easy. I apologize to myself for not starting early. But better late, than never.
I have worked on compilers for a long time. So, while exploring a new language, I try to think how an interpreter or compiler might do the trick. After learning syntax, I started exploring how React is improving performance. And I encountered Virtual DOM.
[In this article, I will try to explain how virtual DOM might work with respect to a compiler. I will not go into any specific details. I am still learning how React is implemented. I will keep posting details.]
Document Object Model or DOM
The above operation is expensive as the browser manipulating the DOM tree each time some changes are applied. I believe the browser has to do some smart computation for identifying the changed element and making the changes (like suppose, keeping a reference to each element in a hash map. I am still exploring it.). It is definitely an expensive operation - time and memory-wise. Also, the browser has other tasks to do like displaying the page.
What is Virtual DOM?
"The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM." - React Documentation .
I did not even try to define it with my words. It is such a concise definition. What I have understood so far - React virtual DOM is an in-memory optimized representation of DOM. And React engine deals with low-level APIs to apply the changes.
How React brings Performance into Picture?
Now, with the above concept, let's bring the compiler into the picture.
Every compiler stores an entire program in some form of representation (Abstract Syntax Tree). I am mapping Virtual DOM to AST (I am still learning how React optimizes). As virtual DOM is an in-memory representation, React engine or compiler can access it fast. Now, let's go step by step.
- Now, if there is some change - React changes virtual DOM.
- React engine compares the virtual DOM with real DOM (aka "diffing") and applies the changes to the changed part only. It finds out the changes.
Now, in JS, the browser is doing all the work. Also, to some extent, it is dependent on how code is being written. In the case of React, React engine is abstracting (remember the word I mentioned at the beginning) out all optimization.
This is one of the reasons, React is faster than traditional HTML JS webpages. I know technically everything I mentioned might not be true and I have not touched upon a lot of things. As I keep exploring, I will keep posting my findings in detail. I will see how my concepts get cleared on the way. If you enjoyed the article, give a like and subscribe to my newsletter.