How to use React virtual DOM

php中世界最好的语言
Release: 2018-05-31 14:22:11
Original
1957 people have browsed it

This time I will show you how to use React virtual DOM and what are the precautions for using React virtual DOM. The following is a practical case, let’s take a look.

In web development, data changes need to be reflected on the UI in real time. At this time, DOM operations need to be performed. However, complex or frequent DOM operations are usually the cause of performance bottlenecks. For this reason, React The mechanism of virtual DOM (Virtual DOM) is introduced.

1. What is virtual DOM?

In React, the result of render execution is not a real DOM node, but a lightweight

JavaScript object, which we call virtual DOM.

Virtual DOM is a highlight of React, with batching (batch processing) and efficient Diff algorithm. This allows us to "refresh" the entire page at any time without worrying about performance issues, and the virtual DOM ensures that only the actual DOM operations are performed on the truly changed parts of the interface. In actual development, you basically don’t need to care about how the virtual DOM works, but understanding its operating mechanism will not only help you better understand the

life cycle of React components, but will also be of great help in further optimizing React programs. help.

2. Virtual DOM VS directly operating the native DOM?

If there is no Virtual DOM, simply reset innerHTML directly. This operation is reasonable when all the data in a large list has changed. However, when only one row of data changes, it also needs to reset the entire innerHTML, which obviously causes a lot of waste.

Compare the redrawing process of innerHTML and Virtual DOM as follows:

innerHTML: render html string Recreate all DOM elements

Virtual DOM: render Virtual DOM diff necessary DOM updates

Compared with DOM operations, js 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 subsequent DOM operations. Of course, someone has done verification and said that the performance of React is not as good as directly operating 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;
  ...
}
Copy after login

In this test case, a String containing 1000 Tags is constructed and added to the DOM tree. , but only one DOM operation was performed. However, in the actual development process, these 1,000 element updates may be distributed in 20 logical blocks, each logical block contains 50 elements. When the page needs to be updated, it will cause the DOM tree to be updated. The above code will approximately become It becomes the following format:

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;
    }
  } 
  ... 
}
Copy after login

Looking at it this way, the performance of React is far better than native DOM operations.

Moreover, the DOM does not belong to Javascript at all (nor does it exist in the Javascript engine). Javascript is actually a very independent engine. DOM is actually a set of APIs introduced by the browser that allow Javascript to operate

HTML documents. In the era of just-in-time compilation, the overhead of calling DOM is very high. The execution of Virtual DOM is entirely in the Javascript engine, and there is no such overhead at all.

React.js has great performance advantages over direct manipulation of native DOM, largely due to the batching and diff of virtual DOM. Batching collects all DOM operations and submits them to the real DOM at once. The time complexity of the diff algorithm has also been reduced from O(n^3) of the standard Diff algorithm to O(n). I’ll leave this to the next blog post.

3. Virtual DOM VS MVVM?

Compared with React, other MVVM frameworks such as Angular, Knockout, Vue, and Avalon all use

data binding: through Directive/Binding objects, observation The data changes and retains the reference to the actual DOM element, and performs corresponding operations when the data changes. MVVM's change checking is at the data level, while React's checking is at the DOM structure level. The performance of MVVM also differs based on the implementation principle of change detection: Angular's dirty check makes any change have a fixed cost of O (watcher count); Knockout/Vue/Avalon all use dependency collection, both at the js and DOM levels. Yes O(change):

  1. Dirty check: scope digest Necessary DOM update

  2. Dependency collection: Re-collect dependencies Necessary DOM update

As you can see, the most inefficient thing about Angular is that any small change has a performance cost related to the number of watchers. but! When all the data changes, Angular actually does not suffer. Dependency collection requires re-collection of dependencies during initialization and data changes. This cost can be almost ignored when a small amount of updates are made, but it will also cause a certain consumption when the amount of data is large.

When MVVM renders a list, since each row has its own data scope, each row usually has a corresponding ViewModel instance, or a slightly lighter "scope that uses prototype inheritance. " object, but there is a price. Therefore, initialization of MVVM list rendering is almost guaranteed to be slower than React, because creating ViewModel / scope instances is much more expensive than Virtual DOM. A common problem for all MVVM implementations here is how to effectively reuse already created ViewModel instances and DOM elements when the data source for list rendering changes, especially when the data is a brand new object. Without any reuse optimization, since the data is "new", MVVM actually needs to destroy all previous instances, recreate all instances, and finally render again! This is why the angular/knockout implementations linked in the title are relatively slow. In contrast, since React's change check is at the DOM structure level, even if it is brand new data, as long as the final rendering result has not changed, there is no need to do useless work.

Both Angular and Vue provide optimization mechanisms for list redrawing, which are "hints" to the framework on how to effectively reuse instances and DOM elements. For example, the same object in the database will become different objects in two front-end API calls, but they still have the same uid. At this time, you can prompt track by uid to let Angular know that the two objects are actually the same data. Then the instances and DOM elements corresponding to the original data can be reused, and only the changed parts need to be updated. Or, you can also directly track by $index to perform "in-place reuse": reuse directly based on the position in the array. In the example given in the question, if the angular implementation adds track by $index, subsequent redrawing will not be much slower than React. Even in the dbmonster test, Angular and Vue are faster than React after using track by $index: dbmon (note that the default version of Angular is not optimized, the optimized version is below)

When comparing performance, it is necessary to divide Understand the different occasions of initial rendering, small data update, and large data update. Virtual DOM, dirty checking MVVM, data collection MVVM have different performances and different optimization requirements on different occasions. In order to improve the performance of small data updates, Virtual DOM also needs targeted optimization, such as shouldComponentUpdate or immutable data.

  1. Initial rendering: Virtual DOM > Dirty Check>= Dependency Collection

  2. Small amount of data update: Dependency Collection>> Virtual DOM Optimization > Dirty Check (cannot be optimized) > Virtual DOM No Optimization

  3. Large data update: Dirty Check Optimization>= Dependency Collection Optimization> Virtual DOM (Cannot/No need to optimize )>> MVVM without optimization

  4. (This paragraph draws on the relevant answers from Zhihu)

  5. four , Misunderstanding of React virtual DOM?

    React never said "React is faster than native DOM manipulation". React guarantees us that it can still provide us with decent performance without 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 based on the answer on Zhihu: No framework can optimize DOM operations faster than purely manual operations, because the DOM operation layer of the framework needs to cope with any operations that may be generated by the upper-layer API, and its implementation must be universal. For any benchmark, I can write manual optimizations that are faster than any framework, but what's the point? When building a practical application, do you do manual optimization for every place? For maintainability reasons, this is obviously not possible.

    I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

    Recommended reading:

    Implementation of uploading pictures with back-end code in WeChat mini program

    Practical practice of uploading pictures in WeChat mini program Case Analysis

    The above is the detailed content of How to use React virtual DOM. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template