Some time ago, I did a technical sharing of “ReactNative principle analysis” in the company. Due to the lack of detailed PPT, I sorted out a series of articles on ReactNative principle analysis to meet the needs of some partners, hoping that we could have a systematic and comprehensive understanding of the underlying principle of ReactNative.

  • “ReactNative Principle” startup process
  • “ReactNative principle” JS layer rendering diff algorithm
  • “ReactNative Principle” Native layer rendering process

After ReactNative is started, the JS code in the JsBundle is loaded and the JS layer is rendered.

Why talk about ReactNative JS layer rendering, focus on the Diff algorithm?

After writing React for Web and ReactNative, you can obviously feel that the lifecycle and refresh mechanism are almost the same except for the different component names. This is what Facebook calls “Learn once, write anywhere”. If you can write React, you can develop both Web and ReactNative without pressure. The core advantages of React framework over traditional pure JS development are componentalization and diff algorithm refresh mechanism, which greatly improve development efficiency and program rendering performance

React does not operate on all real DOM nodes immediately when refreshing the setState interface. Instead, diff algorithm is used to calculate and then operate on DOM nodes with changes (native is used to operate on the native UI layer). The refreshing steps are as follows:

1. State changes to generate a new Virtual Dom 2. Compare the similarities and differences between Virtual Dom and previous Virtual Dom 3. Generate the difference object 4. Iterate over the difference object and update the real DOMCopy the code

Summary of Virtual Dom

DOM operation is time-consuming. JS objects are used to simulate DOM Tree. When rendering update, JS objects are operated first, and then Virtual DOM of JS objects is rendered into DOM Tree in batches, so as to reduce DOM operation and improve performance.

The whole diff algorithm is based on the Virtual Dom, so what is the Virtual Dom?

The Virtual Dom is essentially a JS object used to simulate the Dom. Generally, there are three attributes: tag, props, and children. Different frameworks use different names for these attributes, but the meanings are the same

Example: For the following code, how to map to the corresponding Virtual Dom?

<A>
  Hello World
  <B>
    <C key="key-C" style={{ width: 100}} / >
    <D key="key-D" style={{ color: 'red' }} />
  </B>
</A>
Copy the code

In this example, the three attributes are analyzed as follows

  • A,B,C,DIt’s a tag
  • key,styleIs the property (props)
  • nodeBIs a nodeAThe children object of
  • nodeCandDIs a nodeBThe children object of
  • Finally, the mapped JS object (Virtual Dom) is as follows:

The React Diff algorithm makes two assumptions

Why does the React Diff algorithm decrease from O(n^3) to O(n) compared to the traditional Diff algorithm?

React reduces unnecessary calculations based on two assumptions

1. Two identical components will generate similar DOM structures, and two different components will generate different DOM structures. 2. A group of child nodes at the same level can be distinguished by unique ids.Copy the code

For hypothesis 1: two identical components, which generally refer to the same class, including the React component officially defined (View, Text) and the programmer-defined component (this is also a reason for the React component development to improve the efficiency of the DIff algorithm).

For hypothesis 2: this generally means using map to traverse the generated ListView or using list components such as ListView/FlatList

The React Diff algorithm is almost optimized based on the above two assumptions. Let’s take a look at the implementation principle of the React Diff algorithm

React Diff algorithm implementation

Based on the above two assumptions, the implementation of React Diff algorithm can be mainly divided into three types: comparison of nodes of the same type, comparison of different node types, and comparison of list nodes. This paper mainly analyzes these three types of cases.

1. Comparison of nodes of the same type

  • Example Change the style attribute of controller A

According to the first half of hypothesis 1, two identical components will generate A similar DOM structure. Since the old and new nodes have the same type (tag is A), the DOM structure does not change. React only resets the style property (styleBefore to styleAfter) to convert nodes and update the interface

  • In this case, the Native updateView will be called to refresh the interface after calculation by such diff algorithm.

2. Comparison of different node types

  • Change node A and its children (shown in red) to the children of node D

To facilitate analysis, the DOM Tree node model is firstly abstracted as follows

In the last sentence of Hypothesis 1, two different components will generate different DOM structures. When it is found that a node does not exist, the node and its child nodes will be completely removed and will not be used for further comparison. Therefore, React will directly delete the previous node, and then create and insert new nodes.

In this example, the left subtree of the root is removed directly (that is, node A and its children B and C are removed first), and then node A and its children B and C are recreated as the right subtree of the root

  • In this case, the Native Manager hildren is called to refresh the interface after the diff algorithm is calculated.

3. Compare list nodes

When rendering list nodes, they usually have the same structure, but the content is slightly different. For example, if a ListView or ListView/FlatList component is traversed by a map, the compiler will give a warning if the key is not written. The corresponding DIff algorithm is very different, and the program performance will also be very different.)

According to hypothesis 2, for a group of sub-nodes at the same level, they can be distinguished by unique keys. Adding unique keys to each node can greatly simplify the DIff algorithm and reduce DOM operations. The comparison of list nodes mainly includes three scenarios: adding nodes, deleting nodes, and sorting nodes. After the CALCULATION of THE DIff algorithm of the JS layer, the Native manageChildren will be invoked to refresh the interface.

3.1 Adding a Node
  • Insert node F between nodes B and C

Each node whether to add unique identification key algorithm implementation and comparison

  1. Without plan one, add only the stability of the key, can’t locate the exact location of the modified, can ordinal comparison before and after the two states (i.e., A, B, C, D, E and A, B, F, C, D, E), when compared to the third, found that C and F are not identical, record, in turn, back D and C, E and D, which are different, are also recorded. Finally, add an E node newly added in the new state, and a total of four DOM operations are required

  2. In scheme 2, if a unique stable key is added, the DOM can be directly found and inserted once

  3. To sum up, it can be found that when nodes are added to the list, there is a unique and stable key, which can reduce DOM operations and thus improve program performance

3.2 Deleting a Node
  • Deleting node B

  1. Without plan one, add only the stability of the key, can’t locate the exact location of the modified, can ordinal comparison before and after the two states (i.e., A, B, C and A, C), when compared to the second, found that B and C are not identical, record, in turn, back found less new than the old state node C, To remove node C in the old state, a total of two DOM operations are required

  2. In scheme 2, if a unique stable key is added, the DOM can be directly deleted and deleted once

  3. To sum up, it can be found that when the list deletes nodes, there is a unique stable key, which can reduce DOM operations and thus improve program performance

3.2 Sorting Nodes
  • Switch the positions of nodes B and C

Each node whether to add unique identification key algorithm implementation and comparison

  1. In scheme 1, without adding keys, specific nodes cannot be located and can only be updated by traversing, comparing and updating one by one. For example, in this case, to swap the positions of nodes B and C of the old AND new DOM, do the following:
1. Compare node C of the new DOM with node B of the old DOM, and node B is updated to node C 2. Node B of the new DOM is compared with node C of the old DOM, and node C is updated to node B.Copy the code
  1. In scheme 2, when there is a unique stable key, specific nodes can be directly located, and the corresponding nodes only need to be sorted. For example, in this example, to switch the positions of B and C, do the following:
1. Switch nodes B and C.Copy the code
  1. In summary, it can be found that in the case of no key, DOM operations need to be performed twice; in the case of key, DOM operations need to be performed only once.

Conclusion: When there is a unique stable key in the list node, adding, deleting and sorting nodes can greatly reduce the number of DOM operations and improve the performance of the program

Finally, why does a key have to be unique and stable?

  1. If the key is not unique (for example, the key values of different nodes are the same) and all components in the list are of the same type, the diff algorithm is the same as that without setting the key. However, if the component types of the lists are different, exceptions such as repeated rendering can occur

  2. If the key is unstable (for example, the key takes index when inserting or deleting nodes), the diff algorithm is the same as that without setting the key


You think it’s nice give me a small onepraiseEncouragement ~

ReactNative principle analysis of the same series of articles:

  • “ReactNative Principle” startup process
  • “ReactNative principle” JS layer rendering diff algorithm
  • “ReactNative Principle” Native layer rendering process

conclusion

If you are also a programmer interested in investment and financial management, welcome to pay attention to my public account “flying dragon at the bottom of the valley”, and become the investment leader of the technology industry.