A brief analysis of react virtual DOM

Source: Internet
Author: User



Reprint: http://www.alloyteam.com/2015/10/react-virtual-analysis-of-the-dom/?hmsr=toutiao.io&bsh_bid=928783684



In web development, the need to reflect changes in the data in real time to the UI requires manipulation of the DOM, but complex or frequent dom operations are often the cause of performance bottlenecks, and react introduces the virtual DOM mechanism.


    1. What is virtual dom?
    2. Virtual Dom VS Direct manipulation of native dom?
    3. Virtual Dom VS MVVM?
    4. Misunderstanding of the react virtual DOM?
First, what is virtual dom?


In react, the result of render execution is not a true DOM node, only a lightweight JavaScript object, which we call virtual DOM.



Virtual Dom is a highlight of react, with batching (batch) and efficient diff algorithm. This allows us to "refresh" the entire page at any time without worrying about performance issues and "without scruple", by the virtual DOM to ensure that the actual DOM operation is performed only on the truly changing parts of the interface. In real-world development, there is no need to care about how virtual DOM works, but understanding its operating mechanism not only helps to better understand the life cycle of the react component, but also helps to further optimize the react program.


Second, virtual Dom VS direct operation of the native DOM?


Without Virtual DOM, simply resetting the InnerHTML is straightforward. This makes sense when all the data in a large list is changed, but when only one row of data changes, it also needs to reset the entire InnerHTML, which obviously creates a lot of waste.



The redraw process for comparing innerhtml and virtual DOM is as follows:



Innerhtml:render HTML string + recreate all DOM elements



Virtual Dom:render Virtual DOM + diff+ necessary DOM update



        and DOM operations, JS The calculation is very cheap. Virtual DOM Render + diff is obviously slower than rendering HTML strings, but it is still a pure JS-level calculation, which is still much cheaper than the DOM operation behind it. Of course, there has been a verification that react performance is not as straightforward as manipulating the real DOM, the code is as follows:


function Raw() { var data = _buildData(),
        html = "";
    ... for(var i=0; i<data.length; i++) { var render = template;
        render = render.replace("{{className}}", "");
        render = render.replace("{{label}}", data[i].label);
        html += render;
    }
    ...
    container.innerHTML = html;
    ...
}



function Raw() { var data = _buildData(), 
        html = ""; 
    ... for(var i=0; i<data.length; i++) { var render = template; 
        render = render.replace("{{className}}", ""); 
        render = render.replace("{{label}}", data[i].label); 
        html += render; if(!(i % 50)) {
            container.innerHTML = html;
        }
    } 
    ... 
}


In this way, the performance of react is much better than the native DOM operation.


Furthermore, DOM is completely out of JavaScript (and does not exist in the JavaScript engine). JavaScript is actually a very independent engine, and Dom is actually a set of APIs for JavaScript to manipulate HTML documents from the browser. In an era of instant compilation, the cost of invoking the DOM is significant. The virtual DOM is executed entirely in the JavaScript engine, with no overhead at all.


React.js has a great performance advantage over direct manipulation of the native DOM, thanks in large part to virtual Dom's batching and diff. The batching collects all DOM operations and submits them to the real DOM at once. The time complexity of the diff algorithm is also reduced from the standard diff algorithm O (n^3) to O (n). Stay here for the next blog to speak alone.











Third, virtual Dom VS MVVM? Compared to React, other MVVM frameworks such as Angular, Knockout, and Vue, Avalon use data binding: by Directive/binding objects, observing data changes and preserving references to actual DOM elements, when data changes The corresponding operation. The change checking for MVVM is data-level, and the React check is the DOM structure level. The performance of MVVM varies according to the implementation principle of the change detection: Angular's dirty check makes any change with a fixed O (Watcher count) price, Knockout/vue/avalon is dependent on the collection, at the JS and DOM levels are O (Chan GE):




    • Dirty Check: Scope digest+ necessary DOM update
    • Dependency collection: Re-collection of dependencies + necessary DOM updates

As you can see, the most inefficient part of Angular is the performance cost associated with any small change and watcher quantity. But! When all the data is changed, Angular is not really a disadvantage. Dependency collection needs to be re-collected when initializing and changing data, which can be negligible at a small update, but consumes when the volume of data is large.
When MVVM renders a list, because each row has its own data scope, it usually has a corresponding ViewModel instance for each row, or a slightly lighter number of "scope" objects that take advantage of the prototype, but at some cost. So, the initialization of the MVVM list rendering is almost certainly slower than React, because creating an viewmodel/scope instance is much more expensive than the Virtual DOM. A common problem with all MVVM implementations here is how to efficiently reuse the ViewModel instances and DOM elements that have been created when the data source changes are rendered in the list, especially when the data is a completely new object. Without any reuse optimizations, because the data is "completely new", MVVM actually needs to destroy all previous instances, recreate all instances, and then render again! This is why the Angular/knockout implementations of links in the topic are relatively slow. In contrast, React's change checking is a DOM-structured one, and even new data, as long as the final rendering has not changed, does not need to be worked hard.
Both Angular and Vue provide an optimization mechanism for list redrawing, which is how the hint framework effectively re-uses instances and DOM elements. For example, the same object in the database, the two-time front-end API calls will be different objects, but they still have the same UID. At this point you can prompt the track by UID to let Angular know that the two objects are actually the same data. So the original data corresponding to the instance and DOM elements can be reused, only need to update the changed parts. Alternatively, you can directly track the by $index to "reuse in situ": directly based on the position in the array to be reused. In the example given in the topic, if the angular implementation plus track by $index, the subsequent redraw will not be much slower than the React. Even in the Dbmonster test, Angular and Vue used track by $index later than React: Dbmon (note Angular default version is not optimized, optimized below)


When comparing performance, it is very clear that the initial rendering, the small amount of data updates, and the large number of data updates are different occasions. Virtual DOM, dirty-check MVVM, data-collection MVVM have different performance and different optimization requirements on different occasions. Virtual DOM also requires targeted optimizations, such as shouldcomponentupdate or immutable data, to improve the performance of small data updates.


    • Initial rendering: Virtual DOM > Dirty Check >= Dependency Collection
    • Small Data Update: Dependency collection >> virtual dom + optimization > Dirty Check (Unable to optimize) > Virtual dom No optimizations
    • Massive Data update: Dirty check + optimized >= dependency collection + optimization > Virtual DOM (No/no optimization) >> MVVM no optimizations


(This paragraph draws on the relevant answers to the knowledge)








Iv. misunderstanding of the react virtual DOM?


React never said "React is faster than native operation DOM." React gives us the assurance that it can still give us a decent performance without the need for manual optimization.


React masks the underlying DOM operations and can describe our purpose in a more declarative way, making the code easier to maintain. The following is a reference to the answer: No framework can be faster than purely manual optimization dom operations, because the framework of the DOM operations layer needs to deal with any of the upper API can produce operations, its implementation must be universal. For any one benchmark, I can write faster manual optimizations than any frame, but what's the point? Do you do manual optimization for every place when building a real application? This is obviously impossible due to maintainability considerations.


In web development, the need to reflect changes in the data in real time to the UI requires manipulation of the DOM, but complex or frequent dom operations are often the cause of performance bottlenecks, and react introduces the virtual DOM mechanism.


    1. What is virtual dom?
    2. Virtual Dom VS Direct manipulation of native dom?
    3. Virtual Dom VS MVVM?
    4. Misunderstanding of the react virtual DOM?




First, what is virtual dom?


In react, the result of render execution is not a true DOM node, only a lightweight JavaScript object, which we call virtual DOM.



Virtual Dom is a highlight of react, with batching (batch) and efficient diff algorithm. This allows us to "refresh" the entire page at any time without worrying about performance issues and "without scruple", by the virtual DOM to ensure that the actual DOM operation is performed only on the truly changing parts of the interface. In real-world development, there is no need to care about how virtual DOM works, but understanding its operating mechanism not only helps to better understand the life cycle of the react component, but also helps to further optimize the react program.


Second, virtual Dom VS direct operation of the native DOM?


Without Virtual DOM, simply resetting the InnerHTML is straightforward. This makes sense when all the data in a large list is changed, but when only one row of data changes, it also needs to reset the entire InnerHTML, which obviously creates a lot of waste.



The redraw process for comparing innerhtml and virtual DOM is as follows:



Innerhtml:render HTML string + recreate all DOM elements



Virtual Dom:render virtual Dom + diff + necessary DOM update



The JS calculation is very inexpensive compared to DOM operations. Virtual DOM Render + diff is obviously slower than rendering HTML strings, but it is still a pure JS-level calculation, which is still much cheaper than the DOM operation behind it. Of course, there has been a verification that react performance is not as straightforward as manipulating the real DOM, the code is as follows:



A brief analysis of react virtual DOM


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.