Home  >  Article  >  Web Front-end  >  Detailed explanation on performance optimization of React components

Detailed explanation on performance optimization of React components

亚连
亚连Original
2018-06-02 09:13:181434browse

This article mainly introduces the performance optimization of React components. Now I will share it with you and give you a reference.

Gartner: "We should forget to ignore small performance optimizations. It can be said that 97% of the time, premature optimization is the root of all evil, and we should care about the other 3 most critical effects on performance. % of the code."

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 requires a re-rendering of the most component , but it does not mean abandoning all the previous rendering content and starting 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 determine the rendering before starting to calculate Virtual DOM The result will not change, then there is no need to perform Virtual DOM calculation and comparison, and the speed will be faster.

2.The default implementation of shouldComponentUpdate

Since it can be determined 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 will proceed. The default value is true. If false is returned, the update will be interrupted;

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

where nextProps For the props passed in for this update, 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 only 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"}}>

To avoid using the above input method, the {color: "red"} object will be re-created each time the rendering occurs, and the reference address will be different each time, which will result in different styleProp each time.

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

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

What if it is a function ?

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

You should avoid using the above function transfer mode, because the value assigned here is an anonymous function, and it is generated during the assignment, and That is to say, each rendering will generate a new function, and this is 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

In the component update process, the updated Virtual DOM will be built and compared with the previous Virtual DOM , so as to find the difference and update it with minimal DOM operations


调和过程:即React更新中对Virtual DOM找不同的过程,通常对比两个N个节点的树形结构的算法,时间复杂度是O(n*3),如果直接

使用默认对比,节点过多的话,需要操作的数量太多,而React不可能采用这种算法;

React实际采用的算法时间复杂度是O(N)(时间复杂度只是对一个算法最好和最差情况下需要的指令操作数量级的估量)

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

节点类型不同的情况

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

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

更新前

 <p>
  <Todos />
 </p>

我们想要更新成这样:

 <span>
   <Todos />
 </span>

>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>

更新后为:

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

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

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

</ul>

(这将暴露一个问题)理想处理方式是,创建一个新的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>

更新后为:

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

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

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

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

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

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

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

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

如何关闭Vue计算属性自带的缓存功能,具体步骤有哪些?

What are the specific methods of using Compass in Vue?

Use the swiper component in vue2.0 to implement carousel (detailed tutorial)

The above is the detailed content of Detailed explanation on performance optimization of React components. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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