• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Reducing Nesting
2
3The view hierarchy can significantly affect application performance. For example, at the 120 Hz refresh rate, a device screen refreshes frames every 8.3 ms. If there are many levels of nested views, the frames may fail to be refreshed within 8.3 ms. As a result, frame loss and frame freezing occur, detracting from user experience. Therefore, it is recommended that you minimize nesting in your code to shorten the refresh time.
4
5## Removing Redundant Levels of Nesting
6
7In the following negative example, the **\<Grid>** component is used to implement a grid, but it is nested inside three levels of **\<Stack>** containers. As a result, the refresh and rendering process takes a long time to complete.
8
9```javascript
10@Entry
11@Component
12struct AspectRatioExample {
13  @State children: Number[] = Array.from(Array(900), (v, k) => k);
14
15  build() {
16    Scroll() {
17      Grid() {
18        ForEach(this.children, (item) => {
19          GridItem() {
20            Stack() {
21              Stack() {
22                Stack() {
23                  Text(item.toString())
24                }
25              }
26            }
27          }
28        }, item => item)
29      }
30      .columnsTemplate('1fr 1fr 1fr 1fr')
31      .columnsGap(0)
32      .rowsGap(0)
33      .size({ width: "100%", height: "100%" })
34    }
35  }
36}
37```
38
39Recommendation: Reduce the redundant nesting of **\<Stack>** containers. In this way, the number of components that each grid item needs to pass is three less, shortening the refresh and rendering time.
40
41```javascript
42// xxx.ets
43@Entry
44@Component
45struct AspectRatioExample {
46  @State children: Number[] = Array.from(Array(900), (v, k) => k);
47
48  build() {
49    Scroll() {
50      Grid() {
51        ForEach(this.children, (item) => {
52          GridItem() {
53            Text(item.toString())
54          }
55        }, item => item)
56      }
57      .columnsTemplate('1fr 1fr 1fr 1fr')
58      .columnsGap(0)
59      .rowsGap(0)
60      .size({ width: "100%", height: "100%" })
61    }
62  }
63}
64```
65