A page is a DOM tree, when the page changes, it will form another DOM tree, the two trees to make comparisons, the use of the diff algorithm.
The traditional diff algorithm is O (n^3), which is quite complex.
Time complexity is an important factor in detecting an algorithm or a performance.
There is nothing magical about it, it's just a noun.
O (n^3), O (n^2), O (n)
From left to right, time complexity is getting smaller, the smaller the performance the better.
The traditional diff algorithm will be different, react's diff algorithm will first check whether the structure is the same, if different directly destroy the reconstruction.
React changes the diff algorithm from O (n^3) directly to O (n), which greatly improves performance.
DOM nodes in the Web UI have very few cross-level movement operations and are negligible.
Two components with the same class will produce a similar tree structure, and two components with different classes will produce different tree structures. (similar to the virtual DOM node, not to compare, but to directly destroy the previous DOM node, and then add a new DOM node, eliminating the comparison of two DOM trees, improve performance)
For a set of child nodes at the same level, they can be differentiated by a unique ID. (that is, the map loop adds key to this unique identifier)
Based on the above three premise strategies, React the algorithm optimization of tree diff, Component diff and element diff respectively, it is proved that these three premise strategies are reasonable and accurate, which guarantees the performance of the overall interface construction.
Tree diff
Component diff
Element diff
When a node changes from Div to span, simply delete the div node directly and insert a new span node. This is in line with our understanding of real DOM operations. It is important to note that deleting a node means destroying the node completely, instead of following the comparison to see if another node is equivalent to the deleted node. If there are child nodes under the deleted node, the child nodes are also completely deleted, and they are not used for subsequent comparisons. This is why the algorithm can be reduced to O (n) complexity.
The DOM diff algorithm of react actually only compares the trees to the layers.
Reference:
http://www.infoq.com/cn/articles/react-dom-diff/
Https://zhuanlan.zhihu.com/p/20346379?refer=purerender
React diff algorithm