Home  >  Article  >  Web Front-end  >  What are the aspects of performance optimization of react components?

What are the aspects of performance optimization of react components?

php中世界最好的语言
php中世界最好的语言Original
2018-04-12 14:04:101594browse

This time I will bring you Performance optimization of react components. What are the aspects of performance optimization of react components? What are the precautions for performance optimization of react components? The following is a practical case. Let’s take a look.

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. % code "

Don't waste performance optimization energy on code that does not greatly improve overall performance. It is not too early to optimize the parts that have a critical 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 each page update is a re-rendering of the most components, 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 why React renders 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 that the rendering result will not change before starting to calculate the Virtual DOM, then you do not need to perform Virtual DOM calculation and comparison, and the speed will be faster.

2.The default implementation of shouldComponentUpdate

Since we can prevent the rendering of the component before starting to calculate the Virtual DOM and determine that the rendering result will not change, thus improving 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";

That is, a Boolean value is returned 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)
}

NextProps is the props passed in for this update. For this component, the only props that affect the rendering 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'

I will also think that they are the same:

So, 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, they will be considered two different props even if the contents of the objects are exactly the same. 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.

Therefore, if you want to determine that the props of the previous and later object types are the same, you must ensure that the prop points to the same JavaScript object:

<Foo styleProp = {{color: "red"}}>

To avoid using the above passing method, the {color: "red"} object should be recreated for each rendering, 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 'Single case mode' to ensure that the styleProp passed in points to the same object

What if it is a function?

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

You should avoid using the function transfer mode above, because what is assigned here is an anonymous function, and it is generated during the assignment, which means that a new function will be generated every time it is rendered. 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 the component's lifecycle functions are 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.

同样一个组件的渲染过程也要考虑三个过程:装载阶段、更新阶段、卸载阶段

对于装载阶段,组件无论如何都要彻底渲染一次,从这个React组件往下的所有子组件,都要经历一遍React组件的装载生命
周期,所以并没有多少优化的事情可做。

对于卸载阶段,只有一个生命周期函数componentWillUnmount,这个函数只是清理componentDidMount添加的事件处理监听等收尾工作,所以,也没有什么可优化的空间;

4. React更新阶段的调和(Reconciliation)过程

在组件更新过程,会构建更新Virtual DOM,并将其与之前的Virtual DOM进行比较,从而找出不同之处,使用最少的DOM操作进行更新

调和过程:即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,并没有预期让组将直接访问。            

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue.js的ul-li标签如何仿制select标签

在element-ui中table表格怎样滚动加载

VUE中更改计算属性后select选中值不变的处理方法

The above is the detailed content of What are the aspects of 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