目录

Optimizing Performance Using LazyForEach

Overview

LazyForEach is a lazy loading technology that loads data or resources only when necessary and creates components during each iteration. LazyForEach is usually used if the data volume is large and child components can be reused, such as long lists, grids, and waterfalls. Resource loading is triggered only when a user scrolls the page to the target position. This reduces the component loading time and improves app performance and ultimately user experience.

Principles for LazyForEach

[h2]Rendering Process

In the declarative description statement, ForEach and LazyForEach are used to control the rendering of container components such as lists and grids.

LazyForEach implements on-demand loading. In the case of large amount of list data and complex list components, LazyForEach reduces the time consumed for loading data at a time when the page is started for the first time and reduces the peak memory usage. However, in the process of swiping a long list, new content needs to be continuously loaded as the user keeps swiping. For this reason, additional data requests and processing operations are required, which increases the calculation workload and consequently compromising the performance. To address the issue, using the on-demand loading capability of LazyForEach, which loads data only when the swiping stops or reaches a threshold, helping reduce unnecessary computations and requests and improve performance and user experiences. In a word, in a scenario of implementing on-demand loading, a balance between performance and user experience needs to be comprehensively considered, and loading logic and rendering methods need to be properly optimized, to improve overall performance.

[h2]Rules for Generating Key Values and Creating Components

You are advised to use the Code Linter scanning tool for code inspection, focusing specifically on the @performance/hp-arkui-no-stringify-in-lazyforeach-key-generator rule. If issues related to this rule are identified in the scan results, adjust your code by following the optimization suggestions provided in this section.

When using LazyForEach, you need to implement dataSource, keyGenerator and itemGenerator. dataSource is of the IDataSource type and you need to implement this API. keyGenerator is a function used to generate a unique and persistent key value for each item to identify the corresponding component. You can use it to customize key value generation rules. For details, see Key Generation Rules. The itemGenerator function of LazyForEach is used to create components for each array item of the data source in line with the rules for generating key values. Components can be created for the first rendering or non-first rendering. For details, see Component Creation Rules.

When LazyForEach is used for component reuse, stringify is not recommended in the key-value generation function (keyGenerator). In complex service scenarios, stringify is used to serialize item objects and convert items into character strings. This process consumes a large amount of time and compute resources, resulting in page performance deterioration.

Common Application Scenarios

As one of the common rendering control modes, LazyForEach is commonly used in scenarios such as long list loading and infinite waterfall flow.

[h2]Long List Loading

As one of the most common development scenarios in app development, a long list usually contains thousands of list items. In this scenario, if ForEach is used to load all list items at a time, the rendering takes a long time, compromising user experience. LazyForEach is used to replace ForEach to load list items as required, which improves the list performance. For details about the sample code for lazy data loading, see LazyForEach.

Although on-demand loading of list items can optimize performance of a long list, a list item to display may not be loaded in time if a long list is quickly swiped, causing white blocks and compromising user experience. In ArkUI, the List container provides the cachedCount property. LazyForEach can be used together with the cachedCount property to avoid white blocks. The cachedCount property can be used to set the number of preloaded ListItem or ListItemGroup items in a list. This property takes effect only in LazyForEach. That is, cachedCount can be used only with LazyForEach. In addition to the List container, other containers Grid, Swiper, and WaterFlow also have the cachedCount property. The method of using cachedCount is as follows:

List() {
  // ...
}.cachedCount(3)

In addition, the HarmonyOS app framework provides the component reuse capability, which can be used together with LazyForEach to further optimize the performance of long lists. Component reuse recycles the components to be removed from the component tree. The recycled components enter a recycling buffer. If a component node is to be created, the node in the buffer is reused to shorten the time for re-creating the component. For details about component reuse, see Development Practices of Custom Component Reuse. For details about how to optimize the performance for loading a long list, see Optimizing Frame Loss for Long List Loading.

[h2]Infinite Waterfall Flow

As the name suggests, the content of waterfall mode is arranged from top to bottom. The height of each column may be different, and the overall visual effect of waterfalls is displayed. In waterfalls, LazyForEach is often used to implement on-demand data loading. In addition, the onReachEnd and onScrollIndex methods are added to implement the infinite waterfall flow. For details about waterfall optimization, see Optimizing Waterfall Loading.

[h2]Hybrid Layout List

In a hybrid layout, the container contains different component trees. This scenario is common in complex apps such as e-commerce homepages and social media, where multiple heterogeneous component types, such as image cards, video cards, and text lists, may coexist. Their rendering logic, data structures, and interaction modes are different, posing higher requirements on performance optimization.

1. In scenarios where multiple components are quickly scrolled, ghosting of the previously rendered content may occur during the scrolling process. You are advised to mark @Reusable on the custom component (for details, see @ReusableV2 Decorator: Reusing V2 Components) to enable the component reuse mechanism. In addition, you need to properly handle the component status reset logic in the aboutToReuse lifecycle callbacks to ensure that the component can correctly display new data when it is reused.

2. You are advised to assign different reuse IDs to different types of components. When new data needs to be rendered, the reuse mechanism preferentially searches for an idle component instance in the cache pool corresponding to the reuseId. This ensures that the reused component matches the type of the data to be rendered, preventing unnecessary destruction and reconstruction processes triggered by inconsistent component structures. This reduces performance overhead and potential UI stuttering.

3. To solve the white block issue, use the pre-loading mechanism and LazyForEach together with the cachedCount attribute to build and cache complex nested component instances that are about to enter the viewport during off-peak hours of the rendering thread. This effectively avoids visual blankness caused by time-consuming component creation in high-speed scrolling scenarios.

Common Failure Scenarios

[h2]Restrictions

For details about the restrictions on the use of LazyForEach, see Constraints. Common restrictions are as follows:

[h2]Failure Check Methods

If LazyForEach becomes invalid, rendering errors and frame freezing may occur. You can use logs and Profiler to locate the fault. Common methods for checking whether LazyForEach is invalid are as follows:

  1. View the logs to check the creation of key values and child components. The following is an example. You need to check whether the same key value exists in the logs and whether the number of times that child components appear is inconsistent with the actual number.
    LazyForEach(this.data, (lazyForEachItem: string) => {
      ListItem() {
        Row() {
          Text(lazyForEachItem).fontSize(50)
        }.margin({ left: 10, right: 10 })
      }.onAppear(() => {
        // Record the number of times the component is created through onAppear
        console.info('appear:' + lazyForEachItem);
      })
    }, (item: string) => {
      // Print the key value in the keyGenerator function
      console.info('key:' + item);
      return item;
    })
  2. Use the Profiler tool to capture traces to determine the number of times that a child component is created. As shown in the following figure, a large number of BuildLazyItem slices exist in the frame. Each BuildLazyItem corresponds to a child component creation. The comparison result shows that the LazyForEach on-demand loading fails. For details about optimization, see Performance Analysis.

  3. Use HiDumper to view the component information and determine the rendering status of the component. For details about HiDumper, see hidumper.

[h2]Lazy Loading Failure in Hybrid Layouts

When no explicit layout constraints are set for the parent container, the child container attempts to calculate and instantiate all list items to complete its own layout measurement. In this case, even if you use LazyForEach for lazy loading, the system will create thousands of component instances in an instant, causing the lazy loading mechanism to fail.

Scenario: When a container with infinite scrolling capability is nested with a container that supports on-demand loading, if the vertical layout space of the child container is not explicitly constrained, lazy loading will fail.

Root cause: By default, the parent container provides infinite mapping space in the main axis (vertical direction), which prevents the internal child container from defining the viewport boundary.

Result: The on-demand instantiation logic of LazyForEach strongly depends on viewport cropping. Without boundary constraints, thousands of components in the data source are instantiated instantaneously within a single layout frame. This leads to the breakdown of the lazy loading mechanism, severe UI thread blocking, instantaneous memory overflow (OOM), and exponential increase in the time to interactive (TTI) for the first screen rendering.

Solution:

Set a specific height() for the internal child container or use percentage and layoutWeight(1) to limit the viewport boundary.

Use LazyVGridLayout as the child component of WaterFlow or FlowItem, and use attributes such as columnsTemplate, rowsGap, and columnsGap to implement complex nested layouts, preventing lazy loading failures.

[h2]Rendering Disorder Caused by the Same Key Value

In the key value generation rule of LazyForEach, each item corresponds to a unique and persistent key value, which is used to identify the corresponding component. When different data items have the same key value, the framework may fail to find the correct data item. As a result, an error occurs when rendering a child component. For details about how to handle rendering disorder caused by incorrect key values, see the example in Initial Render.

[h2]Frame Loss Due to Complex ListItem

When LazyForEach is used, a large amount of layout calculation is time-consuming due to a complex child component ListItem when the child component is created. As a result, the frame is lost. The key code is as follows:

@Entry
@Component
struct Index {
  private data: MyDataSource = new MyDataSource();

  aboutToAppear() {
    for (let i = 0; i <= 30; i++) {
      this.data.pushData(`Hello ${i}`)
    }
  }

  build() {
    List({ space: 3 }) {
      LazyForEach(this.data, (lazyForEachItem: string) => {
        ListItem() {
          Column() {
            ForEach(this.data.getAllData(), (forEachItem: string) => {
              ListItem() {
                Row() {
                  Text(lazyForEachItem + forEachItem).fontSize(50)
                    .onAppear(() => {
                      console.info("appear:" + lazyForEachItem)
                    })
                }.margin({ left: 10, right: 10 })
              }
            }, (item: string) => item)
          }
        }
      }, (item: string) => item)
    }.cachedCount(5)
  }
}

[h2]On-Demand Loading Failure Due to the Scroll-Nested List

When the List component is nested in the Scroll container, during long list loading, all list items are loaded by default if the width and height of the list are not specified. As a result, the on-demand loading fails, and the app may even freeze or crash. For details, see Layout Optimization.

[h2]On-Demand Loading Failure Because the Height Is Not Set in GridItem

When the Grid container is used, all child components are loaded if the height is not set in GridItem. The child components in the Grid display area are loaded if the width and height are set in GridItem. The reference code is as follows:

@Entry
@Component
struct Index {
  private data: MyDataSource = new MyDataSource();
  private scroller: Scroller = new Scroller();

  aboutToAppear() {
    for (let i = 0; i <= 30; i++) {
      this.data.pushData(`Hello ${i}`)
    }
  }

  build() {
    Column() {
      Grid(this.scroller) {
        LazyForEach(this.data, (lazyForEachItem: string) => {
          GridItem() {
            Text(lazyForEachItem)
              .fontSize(50)
              .width('100%')
          }
          .onAppear(() => {
            console.info("appear:" + lazyForEachItem)
          })
        }, (item: string) => {
          return item;
        })
      }
      .columnsTemplate('1fr')
      .enableScrollInteraction(true)
      .width('100%')
      .height(800)
      .cachedCount(5)
    }
    .width('100%')
    .height(700)
  }
}

Sample Code