I am using react to build my own web app, but I am wondering how does the following assumption make react diff faster. In other words, what does react base this assumption on?
Two elements of different types will produce different trees.
That assumption enables React to find out minimum number of operations to transform one DOM tree into another one in O(n) time.
However, the state of the art algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree. If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive.
By assuming that elements of different types have different trees, react will save valuable computation time by avoiding too many comparisons to convert one tree into another. So without this if you have the following structure
<div>
<span> </span>
<span> </span>
</div>
and if your new structure is
<span>
<span> </span>
<div> </div>
</span>
React will now have to compare whether the first span child was there or not. Then it will have to compare whether second child div is there or not; now it finds that it wasn't there so it will have to only change the second div along with the outer parent tag. (Imagine doing this for 1000 elements)
They have also mentioned
In practice, these assumptions are valid for almost all practical use cases.
And from my experience in almost all cases it is always true.