How is react diffing algorithm faster than manual DOM manipulation?

257 Views Asked by At

I love React! However, I started programming after the advent of React so I never really had the first hand experience of working with vanilla JS for a app in production. So, as I was going down the path of understanding why React was invented, I am curious if people think that React is faster than manual dom manipulation (the vanilla way)? I understand that React makes coding less error prone, and scalable but can't wrap my head around whether that actual dom maniuplation is faster.

Because if a developer manually updates a DOM node on some event, then there is no reason to compare it even against a virtual DOM. Comparing against a virtual dom has to be done through an algorithm. Even if the algorithm takes little time, isn't manual dom manipulation (without having to compare anything) still faster?

Thanks in advance, and please excuse any ignorance on my part. I am trying to learn :)

2

There are 2 best solutions below

0
Saadman Islam Khan On

Sort of found an answer to my own question. React basically does batch updates so it really is not just updating the DOM immediately when a state change call occurs. Therefore when we call setState(..), the DOM and the state in question is not immediately updated but queued up.

All the state change calls in the current execution block (for example if the interactivity that caused the state change was a button click, the function triggered for that OnClick event would be the execution block), is queued up in that batch.

After which, React goes into a Reconcilation stage, where it uses its diffing algorithm to compare the current virtual dom changes (containing the mutations) to the previous, and then finds the minimal set of DOM nodes that needs to be updated. Part of the reconcilation step is also to check for the impact of these state changes on the children custom components. Thereby, the algorithm recursively does the same on the child components and then finally when it hits the base case, it stops.

At this point in time, our updated virtual dom has all the dom node changes that are impacted. The last step is to update the changes to the Real DOM.

So this procedure makes re-render really effective. We are doing the most expensive operation i.e the actual DOM manipulation at the end, with the whole but minimal set of DOM nodes. :)

This JsConf talk was great, so I want to mention it here: https://www.youtube.com/watch?v=x7cQ3mrcKaY

0
nawfel bgh On

Short answer is that React diff algorithm was never faster than well written DOM manipulation. Also, many frameworks without VDOM are faster than React.

See: https://krausest.github.io/js-framework-benchmark/current.html

This question reminds me of the tale of the golden tooth: You should ask "is it?" before asking "why is it?".