• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 优化布局性能
2
3## 背景介绍
4
5应用开发中的用户界面(UI)布局是用户与应用程序交互的关键部分。使用不同类型的布局可以将页面排布的更加美观,但也容易带来不合理的布局。不合理的布局虽然能在界面显示上达到相同效果,但是过度的布局计算,界面嵌套带来了渲染和计算的大量开销,造成性能的衰退,本文重点介绍了几种常见的布局功能和适用场景,同时提供了几种优化布局结构的方法。
6
7## 常用布局
8
9布局是UI的必要元素,它定义了组件在界面中的位置。ArkUI框架提供了多种布局方式,除了基础的[线性布局](../ui/arkts-layout-development-linear.md)([Row](../reference/arkui-ts/ts-container-row.md)/[Column](../reference/arkui-ts/ts-container-column.md))、[层叠布局](../ui/arkts-layout-development-stack-layout.md)([Stack](../reference/arkui-ts/ts-container-stack.md))、[弹性布局](../ui/arkts-layout-development-flex-layout.md)([Flex](../reference/arkui-ts/ts-container-flex.md))、[相对布局](../ui/arkts-layout-development-relative-layout.md)([RelativeContainer](../reference/arkui-ts/ts-container-relativecontainer.md))、[栅格布局](../ui/arkts-layout-development-grid-layout.md)([GridCol](../reference/arkui-ts/ts-container-gridcol.md))外,也提供了相对复杂的[列表](../ui/arkts-layout-development-create-list.md)([List](../reference/arkui-ts/ts-container-list.md))、[网格](../ui/arkts-layout-development-create-grid.md)([Grid](../reference/arkui-ts/ts-container-grid.md)/[GridItem](../reference/arkui-ts/ts-container-griditem.md))、[轮播](../ui/arkts-layout-development-create-looping.md)([Swiper](../reference/arkui-ts/ts-container-swiper.md))。
10
11## 优化布局结构
12
13### 减少嵌套层级
14
15布局的嵌套层次过深会导致在创建节点及进行布局时耗费更多时间。因此开发者在开发时,应避免冗余的嵌套或者使用扁平化布局来优化嵌套层次。
16
17**避免冗余的嵌套**
18
19冗余的嵌套会带来不必要的组件节点,加深组件树的层级。例如,内部容器和外部容器是相同的布局方向,内部容器形成的布局效果可以用外部容器代替,对于这类冗余的容器,应该尽量优化,减少嵌套深度。
20
21反例:
22
23使用了Grid来实现一个网格,但在外层套了3层包含不同属性参数的Stack容器:
24
25```ts
26@Entry
27@Component
28struct AspectRatioExample12 {
29    @State children: Number[] = Array.from(Array<number>(900), (v, k) => k);
30
31    build() {
32      Scroll() {
33      Grid() {
34        ForEach(this.children, (item: Number[]) => {
35          GridItem() {
36            Stack() {
37              Stack() {
38                Stack() {
39                  Text(item.toString())
40                }.size({ width: "100%"})
41              }.backgroundColor(Color.Yellow)
42            }.backgroundColor(Color.Pink)
43          }
44        }, (item: string) => item)
45      }
46      .columnsTemplate('1fr 1fr 1fr 1fr')
47      .columnsGap(0)
48      .rowsGap(0)
49      .size({ width: "100%", height: "100%" })
50    }
51  }
52}
53
54```
55
56通过查看组件树结构,发现三层Stack容器设置了不同的属性参数,可以使用GridItem的属性参数实现同样的UI效果。因此,三层Stack容器是冗余的容器,可以去掉,只留下GridItem作为组件节点。
57
58
59```
60└─┬Scroll
61  └─┬Grid
62    ├─┬GridItem
63    │ └─┬Stack
64    │   └─┬Stack
65    │     └─┬Stack
66    │       └──Text
67    ├──GridItem
68    ├──GridItem
69```
70
71正例:
72
73通过减少冗余的Stack容器嵌套,每个GridItem的组件数比上面少了3个:
74
75```ts
76@Entry
77@Component
78struct AspectRatioExample11 {
79  @State children: Number[] = Array.from(Array<number>(900), (v, k) => k);
80
81  build() {
82    Scroll() {
83      Grid() {
84        ForEach(this.children, (item: Number[]) => {
85          GridItem() {
86            Text(item.toString())
87          }.backgroundColor(Color.Yellow)
88        }, (item: string) => item)
89      }
90      .columnsTemplate('1fr 1fr 1fr 1fr')
91      .columnsGap(0)
92      .rowsGap(0)
93      .size({ width: "100%", height: "100%" })
94    }
95  }
96}
97```
98
99通过查看该组件树层级结构如下:
100
101```
102└─┬Scroll
103  └─┬Grid
104    ├─┬GridItem
105    │ └──Text
106    ├──GridItem
107    ├──GridItem
108```
109
110**使用扁平化布局优化嵌套层级**
111
112开发者在实现自适应布局的时候,常使用Flex来达到弹性效果,这可能会造成多级嵌套。建议采用相对布局RelativeContainer进行扁平化布局,有效减少容器的嵌套层级,减少组件的创建时间。
113
114例如,以下是一个自适应的效果:
115
116![输入图片说明](figures/layout-ui-view.png)
117
118反例:
119
120下述代码使用线性布局实现以上UI:
121
122```ts
123@Entry
124@Component
125struct MyComponent {
126  build() {
127    Row() {
128      Column() {
129        Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
130          Text('张')
131          // 属性参数见正例
132        }
133        .width("40vp")
134        .height("40vp")
135      }.height("100%").justifyContent(FlexAlign.Center)
136      //body
137      Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start }) {
138          Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center }) {
139          Flex({ direction: FlexDirection.Row,
140            justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
141            //Phone number or first name
142            Text('张三')
143             // 属性参数见正例
144
145            //Date Time
146            Text('2分钟前')
147             // 属性参数见正例
148             }
149          .width("100%").height(22)
150
151          Row() {
152            Text() {
153              //Content Abbreviations for Latest News
154              Span('Hello World'.replace(/[\r\n]/g, " "))
155                .fontSize("14fp")
156                .fontColor('# 66182431')
157            }
158            .maxLines(1)
159            .textOverflow({ overflow: TextOverflow.Ellipsis })
160          }
161          .alignSelf(ItemAlign.Start)
162          .alignItems(VerticalAlign.Top)
163          .width("100%")
164          .height(19)
165          .margin({ top: "2vp" })
166        }.width("100%")
167        .height("100%")
168      }
169      .layoutWeight(1)
170      .height("100%")
171      .padding({ left: "12vp" })
172    }
173    .alignItems(VerticalAlign.Top)
174    .width("100%")
175    .height("100%")
176  }
177}
178```
179
180通过查看该组件树层级结构如下:
181
182```
183└─┬Row
184  ├──┬Column
185  │  └─┬Flex
186  │    └──Text
187  └─┬Flex
188    └─┬Flex
189      │ └─┬Flex
190      │   ├──Text
191      │   └──Text
192      └─┬Row
193        └──Text
194```
195
196为了将4个元素放到合适的位置,开发者使用了11个组件,树深度为5,实际上是不合理的。
197
198分析元素之间的布局关系可以得到如下:
199
200![输入图片说明](figures/layout-relative-view.png)
201
202正例:
203
204从上图得到一个明确的相对布局位置关系,该场景可以使用相对布局的形式来优化,具体代码实现如下:
205
206```ts
207@Entry
208@Component
209struct MyComponent {
210  build() {
211    Row() {
212      RelativeContainer() {
213        Text('张')
214          .fontSize('20.0vp')
215          .fontWeight(FontWeight.Bold)
216          .fontColor(Color.White)
217          .height('40vp')
218          .width('40vp')
219          .textAlign(TextAlign.Center)
220          .clip(new Circle({ width: '40vp', height: '40vp' }))
221          .backgroundColor(Color.Green)
222          .alignRules({
223            center: { anchor: "__container__", align: VerticalAlign.Center },
224            left: { anchor: "__container__", align: HorizontalAlign.Start }
225          })
226          .id('head')
227        Text('张三')
228          .fontSize('16.0fp')
229          .textOverflow({ overflow: TextOverflow.Ellipsis })
230          .fontColor('# ff182431')
231          .maxLines(1)
232          .fontWeight(FontWeight.Medium)
233          .padding({ left: '12vp' })
234          .height(22)
235          .alignRules({
236            top: { anchor: 'head', align: VerticalAlign.Top },
237            left: { anchor: 'head', align: HorizontalAlign.End }
238          })
239          .id('name')
240        Text('2分钟前')
241          .fontColor('# 66182431')
242          .fontSize('12fp')
243          .maxLines(1)
244          .height(22)
245          .alignRules({
246            top: { anchor: 'head', align: VerticalAlign.Top },
247            right: { anchor: '__container__', align: HorizontalAlign.End }
248          })
249          .id("time")
250        Text() {
251          //Content Abbreviations for Latest News
252          Span('Hello World'.replace(/[\r\n]/g, " "))
253            .fontSize('14fp')
254            .fontColor('# 66182431')
255        }
256        .maxLines(1)
257        .textOverflow({ overflow: TextOverflow.Ellipsis })
258        .width('100%')
259        .height(19)
260        .margin({ top: '2vp' })
261        .padding({ left: '12vp' })
262        .alignRules({
263          top: { anchor: 'name', align: VerticalAlign.Bottom },
264          left: { anchor: 'head', align: HorizontalAlign.End }
265        })
266        .id('content')
267      }
268      .width('100%').height('100%')
269      .border({ width: 1, color: "# 6699FF" })
270    }
271    .height('100%')
272  }
273}
274```
275
276通过减少嵌套层数后可以发现,布局实现了相同的效果,但是组件层级减少了3层,使用组件数也减少了6个。
277
278```
279└─┬RelativeContainer
280  ├──Text
281  ├──Text
282  ├──Text
283  └──Text
284```
285
286从上述案例中可以看到,使用扁平化布局逻辑概念设计更清晰,避免使用不参与绘制的布局组件,优化性能并减少占用内存。这种将一棵深度很高的UI树,改造为将内容排布到同一个节点下的思路,为扁平化布局。如下图所示,采用扁平化布局去除了中间冗余的两层布局节点。
287
288![输入图片说明](figures/layout-relative-introduce.png)
289
290使用扁平化布局推荐使用[RelativeContainer](../reference/arkui-ts/ts-container-relativecontainer.md)、[绝对定位](../reference/arkui-ts/ts-universal-attributes-location.md)、[自定义布局](../reference/arkui-ts/ts-custom-component-lifecycle.md)、[Grid组件](../reference/arkui-ts/ts-container-grid.md)等
291
292### 使用高性能布局组件
293
294**使用Column/Row替换Flex容器**
295
296如果使用Flex布局容器,只是为了实现横向或者纵向的布局。那直接使用Row、Column容器反而能够提升渲染性能。关于Flex带来的性能影响可以参考《[Flex布局性能提升使用指导](flex-development-performance-boost.md)》。
297
298使用Column、Row替换Flex容器组件避免二次渲染的案例见:《[性能提升的其他方法](arkts-performance-improvement-recommendation.md)》
299
300**适当减少使用if/else条件渲染**
301
302在ArkUI的build函数里,if/else也会被当成一个组件,在组件树上也是一个节点。对于一些在不同条件下展示不同效果的场景,基本布局不变,能够通过改变属性来进行控制界面变更的场景下,尽量减少if/else的方式来进行界面内容的切换,因为使用if/else不仅会增加一层节点,而且还有可能造成界面的重排与重绘。
303
304反例:
305
306下述代码中通过判断isVisible的值控制Image组件显示,这会导致在切换选择的过程中,不停创建和销毁Image组件元素。
307
308```ts
309@Entry
310@Component
311struct TopicItem {
312  @State isVisible : Boolean = true;
313
314  build() {
315    Stack() {
316      Column(){
317        if (this.isVisible) {
318          Image($r('app.media.icon')).width('25%').height('12.5%')
319          Image($r('app.media.icon')).width('25%').height('12.5%')
320          Image($r('app.media.icon')).width('25%').height('12.5%')
321          Image($r('app.media.icon')).width('25%').height('12.5%')
322        }
323      }
324      Column() {
325        Row().width(300).height(200).backgroundColor(Color.Pink)
326      }
327    }
328  }
329}
330```
331
332下图为isVisible值不同时组件树的情况:
333
334```
335isVisible为true:
336└─┬Stack
337  ├─┬Column
338  │ ├──Image
339  │ ├──Image
340  │ ├──Image
341  │ └──Image
342  └─┬Column
343    └──Row
344
345isVisible为false:
346└─┬Stack
347  ├──Column
348  └─┬Column
349    └──Row
350```
351
352正例:
353
354下面例子通过visibility属性来控制图片的显隐,避免if/else条件渲染可能带来的重排与重绘。
355
356```ts
357@Entry
358@Component
359struct TopicItem {
360  @State isVisible : Boolean = true;
361
362  build() {
363    Stack() {
364      Column(){
365          Image($r('app.media.icon'))
366            .width('25%').height('12.5%').visibility(this.isVisible ? Visibility.Visible : Visibility.None)
367          Image($r('app.media.icon'))
368            .width('25%').height('12.5%').visibility(this.isVisible ? Visibility.Visible : Visibility.None)
369          Image($r('app.media.icon'))
370            .width('25%').height('12.5%').visibility(this.isVisible ? Visibility.Visible : Visibility.None)
371          Image($r('app.media.icon'))
372            .width('25%').height('12.5%').visibility(this.isVisible ? Visibility.Visible : Visibility.None)
373      }
374      Column() {
375        Row().width(300).height(200).backgroundColor(Color.Pink)
376      }
377    }
378  }
379}
380```
381
382说明:上述情况考虑的是性能优先的场景,而当开发者优先考虑内存时,建议使用if/else控制图片的显隐。
383
384## 优化布局工具介绍
385
386[DevEco Studio](../quick-start/deveco-studio-user-guide-for-openharmony.md)内置ArkUI Inspector工具,开发者可以使用ArkUI
387Inspector,在DevEco Studio上查看应用在真机上的UI显示效果。利用ArkUI Inspector工具,开发者可以快速定位布局不理想或其他UI相关问题,同时也可以观察和了解不同组件之间的布局关系和属性。