目录

Optimizing Frame Loss During Swiper Component Loading

Overview

During development, the Swiper component is usually used to implement page swiping on home screen, Gallery, or other applications. In general cases, the on-demand loading rule is adopted for the Swiper component. This means that, a new page is loaded and rendered only when it is about to be displayed. In complex page scenarios, the loading process can be prolonged, leading to frame freezing during swiping. This not only undermines the swiping experience but also creates a significant performance bottleneck for the application.

This topic describes how to optimize Swiper performance.

LazyForEach

[h2]Principles

LazyForEach iterates data from the provided data source on demand and create corresponding components during each iteration. When the Swiper component uses LazyForEach to implement lazy loading, it creates child components based on the visible area and destroys them when they are swiped out of this area, thereby reducing memory consumption. The development of the Swiper component is a scenario of loading swiping containers. For details about the principles of lazy loading, see Performance Optimization for Loading a Long List—LazyForEach.

[h2]Scenario Case

To show the performance difference between the Swiper components using ForEach and LazyForEach, simulate a quiz test locally.

The core code of the child component in Swiper is as follows:

@Reusable
@Component
struct QuestionSwiperItem {
  @State itemData: Question | null = null;

  aboutToReuse(params: Record<string, Object>): void {
    this.itemData = params.itemData as Question;
  }

  build() {
    Column() {
      Text(this.itemData?.title)
        // ...
      Image(this.itemData?.image)
        // ...

      Column({ space: 16 }) {
        // ...
      }
      .width('100%')
      .alignItems(HorizontalAlign.Start)
    }
    // ...
  }
}

The core code of the main page of the Swiper component is as follows:

Table 1 Performance comparison between ForEach and LazyForEach upon a total number of 1000 questions

Loading Mode

Full Display Time

Frame Loss Rate

Exclusive Memory

ForEach

951 ms

8.5%

200 MB

LazyForEach

280.6 ms

0.0%

25.18 MB

According to the table, when the number of the child components of Swiper exceeds 100, using LazyForEach can improve the frame rate by more than 30% and reduce the memory usage by more than 20%.

Caching Data Items

[h2]Principles

When using LazyForEach, you can set cachedCount to specify the number of cache items. For details about the principles, see Caching List Items in Optimizing Long List Loading.

[h2]Application Scenarios

This property is recommended in scenarios where time-consuming loading is involved, especially in the following scenarios:

[h2]Scenario Case

The following example simulates a scenario where the child components of the Swiper component contain a large number of image resources. The details are as follows:

The core code of the child component in Swiper is as follows:

@Component
struct SwiperItem {
  private data: number[] = [];
  private myIndex: number = 0;
  // Construct data
  private imgURL: string[] = Constant.imgURL;

  aboutToAppear(): void {
    for (let i = 0; i < 50; i++) {
      this.data.push(i);
    }
  }

  build() {
    Column() {
      List({ space: 20 }) {
        ForEach(this.data, (index: number) => {
          ListItem() {
            Image(this.imgURL[this.myIndex * 50 + index])
              .objectFit(ImageFit.Contain)
              .width("100%")
              .height("100%")
          }
          .aspectRatio(1)
          .border({ width: 2, color: Color.Green })
        }, (index: number) => index.toString());
      }
      // ...
    }
    // ...
  }
}

The core code of the main page of the Swiper component is as follows:

@Component
struct TestCodeTwo {
  private dataSrc: NumberDataSource = new NumberDataSource();

  aboutToAppear(): void {
    for (let i = 0; i < 20; i++) {
      this.dataSrc.addData(i, i);
    }
  }

  build() {
    Column({ space: 5 }) {
      Swiper() {
        LazyForEach(this.dataSrc, (item: number, index: number) => {
          SwiperItem({
            myIndex: index
          });
        }, (item: number) => item.toString());
      }
      .cachedCount(1)
      .autoPlay(true)
      .interval(1000)
      .duration(100)
      // ...
    }.width('100%')
    .margin({ top: 5 })
  }
}

To test the impact of different cache sizes on the performance, set cachedCount to 1, 2, 4, and 8, respectively.

Table 2 Comparison between performance data upon different cachedCount values

Cache Count

1

2

4

8

Frame loss rate

3.0%

3.3%

3.1%

3.0%

Exclusive memory

64.36 MB

117.39 MB

214.32 MB

377.38 MB

The test results indicate that as the value of cachedCount increases, the application's memory usage rises significantly, while the frame rate does not see a corresponding substantial improvement.

In the continuous swiping scenario where one child component of Swiper is displayed per screen, set cachedCount to 1 or 2.

The number of caches is for reference only. The optimal number of caches varies with the application settings. Therefore, you need to test the application to determine the optimal number of caches.

Preloading Data

In the fling scenario, the Swiper component provides the onAnimationStart() callback API, which is triggered when the animation starts. In this case, the logic for switching the animation is executed in the rendering thread. The main thread can load the resources required by the child components in this period, such as images and network resources, to reduce the time required for preloading nodes in the cachedCount range. The onAnimationStart callback is triggered only when the animation switching begins after the user stops swiping, not during the swiping phase itself.

[h2]Scenario Case

When a child component of the Swiper component is constructed for the first time (aboutToAppear() is executed.), check whether the image resource exists in the Swiper data. If not, download the image resource and then construct the node.

@Reusable
@Component
struct PreloadSwiperItem {
  // ...

  aboutToAppear(): void {
    hiTraceMeter.startTrace('preloadData', 1);
    // ...
    if (!this.swiperData.pixelMap) {
      ImageUtils.getPixelMap(IMAGE_URL, (pixelMap: PixelMap) => {
        this.swiperData.pixelMap = pixelMap;
      });
    }
    // ...
  }

  onDidBuild(): void {
    hiTraceMeter.finishTrace('preloadData', 1);
  }

  build() {
    Grid() {
      LazyForEach(this.gridDataSource, (item: string) => {
        GridItem() {
          ImageItem({ item: item, swiperData: this.swiperData })
        }
      }, (item: string): string => item.toString())
    }
    .columnsTemplate('1fr 1fr 1fr 1fr')
    // ...
  }
}

When SwiperItem is preloaded, it enters the custom component lifecycle and calls back aboutToAppear. In the aboutToAppear callback, startTrace is used to enable tracing. Then, the build function is invoked to render the component. After the build function is executed, onDidBuild is called back, and finishTrace is used to stop tracing. The noPreLoadData and preLoadData tags are used to collect statistics on the duration of SwiperItem preloading in the two scenarios. For details about the performance measurement, see Performance Tracing.

The core code of the main page of the Swiper component is as follows:

Performance analysis:

As shown in figure 1, the onAnimationStart callback API is not used to preload data. According to the custom trace label H:noPreLoadData, it takes about 50 ms to build the SwiperItem node.

Figure 1 Trace information of the data not preloaded

As shown in figure 2, the onAnimationStart callback API is used to preload data. According to the custom trace label H:preLoadData, it takes about 2 ms to build the SwiperItem node.

Figure 2 Trace information of the data preloaded

According to the detailed trace diagram of H:noPreLoadData, when SwiperItem is preloaded, the aboutToAppear lifecycle callback takes about 48 ms to load image resources.

Figure 3 Trace details of H:noPreLoadData

By using the onAnimationStart callback to preload the resources required by the child components within the subsequent range, the loading time for the child component nodes within the cachedCount range can be effectively reduced.

Reusing Components

When the Swiper component is used in the page turning scenario, its child components are frequently created and destroyed. You can encapsulate the child components into custom components and use @Reusable to reduce the overhead of repeatedly creating and destroying nodes in the ArkUI framework.

For details about the principles and performance analysis, see Performance Optimization for Loading a Long List—Reusing Components.

Summary

This topic describes the following precautions and performance optimization methods for using Swiper in complex page scenarios.

Sample Code