Home > Web Front-end > JS Tutorial > Answers to performance optimization methods for React components

Answers to performance optimization methods for React components

小云云
Release: 2018-03-03 09:00:42
Original
1284 people have browsed it

Don’t waste performance optimization energy on code that has little improvement in overall performance. It is not too early to optimize the parts that have a key impact on performance. Because the most critical part that affects performance often involves the core of the solution and determines the overall architecture, which will be even more involved when it needs to be changed in the future.

1. Performance optimization of a single React component

React uses Virtual DOM to improve rendering performance, although every page update is the most important component Re-rendering, but it does not abandon all the previous rendering content and start over. With the help of Virtual DOM, React can calculate the minimum modification to the DOM tree. This is the secret of React rendering very quickly by default;

However, although Virtual DOM can reduce the amount of each DOM operation to a minimum, calculating and comparing Virtual DOM is still a complicated process;

Of course, if you can calculate Virtual DOM before starting Just judge that the rendering result will not change, then you don't need to perform Virtual DOM calculation and comparison, and the speed will be faster.

2.The default implementation of shouldComponentUpdate

Since it can be judged that the rendering result of the component will not change before starting to calculate the Virtual DOM, To prevent rendering and thereby improve performance, we naturally think of using shouldComponentUpdate(nextProp,nextState)

The shouldComponentUpdate function is called before the render function to determine "when there is no need to re-render";

Returns a Boolean value to determine whether the update continues. The default returns true. If false is returned, the update will be interrupted;


shouldComponentUpdate(nextProp,nextState){
  return (nextProp.completed !== this.props.completed) ||
    (nextProp.text !== this.props.text)
}
Copy after login

where nextProps is this time Update the incoming props. For this component, the only props that affect the rendered content are completed and text. As long as these two props have not changed, shouldComponentUpdate can return false to prevent unnecessary updates.

However, The above comparison is just a 'shallow comparison'. If the type is a basic type, as long as the values ​​are the same, then the 'shallow comparison'

will also consider the two to be the same:

Then, what if the type of prop is a complex object?

For complex objects, the 'shallow comparison' method only checks whether the two props are references to the same object. If not, even if the contents of the objects are exactly the same, they will be considered different. Two props. Then use "deep comparison": But the structure of the object is unpredictable. If you perform "deep comparison" on each field recursively, it will not only make the code more complex, but may also cause performance problems.

So, if you want to determine that the props of the object types before and after are the same, you must ensure that the props point to the same JavaScript object:


<Foo styleProp = {{color: "red"}}>
Copy after login

To avoid using the above input method, the {color: "red"} object will be recreated every time it is rendered, and the reference address will be different every time, which will cause the styleProp to be different every time.


const footStyle = {color: "red"};//确保这个初始化只执行一次,不要放在render函数中
<Foo styleProp = {footStyle}>
Copy after login

Use 'singleton mode' to ensure that the styleProp passed in points to the same object

What if it is a function?


<Foo onToggle={() => onToggleTodo(item.id)}/>
Copy after login

You should avoid using the above function transfer mode, because the assignment here is an anonymous function, and it is generated during the assignment, which means that every Each render generates a new function, and that's the problem.

What if there are a lot of props to be passed?

Well~~If you use React-Redux, there is a default implementation of shouldComponentUpdate.

3. Performance optimization of multiple React components

When a React component is loaded, updated, and unloaded, a sequence of components Lifecycle functions will be called. However, these life cycle functions are for a specific React component function. In an application, there are many React components combined from top to bottom, and the rendering process between them is more complicated.

The rendering process of the same component must also consider three processes: loading phase, update phase, and unloading phase

For the loading phase, the component must be completely rendered no matter what. At one time, all sub-components from this React component downwards have to go through the loading life cycle of the React component, so there is not much optimization to do.

For the uninstallation phase, there is only one life cycle function componentWillUnmount. This function only cleans up the event processing and monitoring added by componentDidMount and other finishing work, so there is no room for optimization;


4. Reconciliation process in the React update phase

During the component update process, the updated Virtual DOM will be built and compared with the previous Virtual DOM , so as to find the differences and use the least DOM operations to update


Reconciliation process: that is, the process of finding differences in Virtual DOM in React update, usually comparing two tree structures of N nodes The time complexity of the algorithm is O(n*3). If you directly


use the default comparison, if there are too many nodes, too many operations are required, and it is impossible for React to adopt this algorithm;


The time complexity of the algorithm actually used by React is O(N) (time complexity is just an estimate of the order of magnitude of instruction operations required by an algorithm in the best and worst cases)


React的Reconciliation算法并不复杂,首先检查两个树形的根节点的类型是否相同,根据相同或者不同有不同的处理方式:

节点类型不同的情况

如果树形节点的类型不相同,那就意味着改动很大,直接认为原来的那个树形结构已经没用,可以扔掉,需要从新构建DOM树,原有的树形上的React组件便会经历“卸载”的生命周期;

也就是说,对于Virtual DOM树这是一个“更新”过程,但是却可能引发这个树结构上某些组件的“装载”和“卸载”过程
如:

更新前


 <p>
  <Todos />
 </p>
Copy after login

我们想要更新成这样:


 <span>
   <Todos />
 </span>
Copy after login

>1. 那么在作比较的时候,一看根节点原来是p,新的是span,类型就不一样了,那么这个算法就废弃之前的p包括里面的所有子节点,从新构建一个span节点和子节点;

>2. 很明显因为根节点不同就将所有的子节点从新构建,这很浪费,但是为了避免O(N*3)的时间复杂度,React这能选择这种比较简单、快捷的方法;

>3. 所以,作为开发者,我们一定要避免上面的浪费的情景出现

节点类型相同的情况

如果两个节点类型相同时,对于DOM元素,React会保留节点对应的DOM元素,只对其节点的属性和内容做对比,然后只修改更新的部分;

节点类型相同时,对于React组件类型,React做得是根据新节点的props去更新节点的组件实例,引发组件的更新过程;

在处理完根节点对比后,React的算法会对根节点的每一个子节点重复一样的操作

多个相同子组件的情况

如果最初组件状态为:


<ul>
  <TodoItem text = "First" />
  <TodoItem text = "Second" />

</ul>
Copy after login

更新后为:


<ul>
  <TodoItem text = "First" />
  <TodoItem text = "Second" />
  <TodoItem text = "Third" />
</ul>
Copy after login

那么React会创建一个新的TodoItem组件实例,而前两个则进行正常的更新过程但是,如果更新后为:


<ul>
  <TodoItem text = "Zero" />
  <TodoItem text = "First" />
  <TodoItem text = "Second" />

</ul>
Copy after login

(这将暴露一个问题)理想处理方式是,创建一个新的TodoItem组件实例放在第一位,后两个进入自然更新过程
但是要让react按照这种方式,就必须找两个子组件的不同之处,而现有计算两个序列差异的算法时间是O(N*2),显然则
不适合对性能要求很高的场景,所以React选择了一个看起来很傻的办法,即挨个比较每个子组件;

React首先认为把text为First的组件的text改为Zero,Second的改为First,最后创建一个text为Second的组件,这样便会破原有的两个组件完成一个更新过程,并创建一个text为Second的新组件

这显然是一个浪费,React也意到,并提供了方克服,不过需要开发人员提供一点帮助,这就是key

Key的使用

key属性可以明确的告诉React每个组件的唯一标识

如果最初组件状态为:


<ul>
  <TodoItem key={1} text = "First" />
  <TodoItem key={2} text = "Second" />

</ul>
Copy after login

更新后为:


<ul>
  <TodoItem key={0} text = "Zero" />
  <TodoItem key={1} text = "First" />
  <TodoItem key={2} text = "Second" />
</ul>
Copy after login

因为有唯一标识key,React可以根据key值,知道现在的第二和第三个组件就是之前的第一和第二个,便用原来的props启动更新过程,这样shouldComponentUpdate就会发生作用,避免无谓的更新;

注意:因为作为组件的唯一标识,所以key必须唯一,且不可变

下面的代码是错误的例子:


<ul>
  todos.map((item,index) => {
      <TodoItem
        key={index}
        text={item.text}
      />
    })
</ul>
Copy after login

使用数组下标作为key值,看起来唯一,但不稳定,因为随着todos数组值的不同,同样一个组件实例在不同的更新过程中数组的下标完全可能不同,把下标当做可以就会让React乱套,记住key不仅要唯一还要确保稳定不可变

需要注意:虽然key是一个prop,但是接受key的组件不能读取key的值,因为key和ref是React保留的两个特殊prop,并没有预期让组将直接访问。

相关推荐:

React组件生命周期详解

React组件Dragact 0.1.4详解

store优化React组件的方法详解

The above is the detailed content of Answers to performance optimization methods for React components. 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