目录

Reducing Application Latency

Overview

In app development for mobile devices, completion latency refers to the time taken from touching a screen to completing UI refresh, and reaching a stable readable state when a user operates a mobile device. Touch completion latency occurs in intra- and inter-page redirection. Completion latency is a critical metric for user experience. It directly influences users' perception of responsiveness and interaction fluidity, and plays a key role in how they evaluate the timeliness and satisfaction of touch interactions.

Shorter latency brings better user experience. However, if the latency is shorter than a certain value, user experience will not be further improved. It is recommended that the response latency of a touch operation in an app or atomic service be less than or equal to 100 ms and the completion latency be less than or equal to 900 ms.

Figure 1 Start and end points of the touch completion
Figure 2 Page transition process

Optimization Solutions for Common Latency Issues

[h2]UI Optimization

The following example shows a common message box list in app development.

As shown in the figure, each subitem in the list view contains elements such as avatar, message red dot, nickname, latest information, and time.

When an app accesses this page, the content is displayed in different styles based on the element data of each message.

Figure 3 Message box list page

In this figure, a single subitem consists of six elements, which are arranged in a linear style. Components such as Image, Badge, and Text may be used.

Figure 4 Single ListItem page

Implementation

Figure 5 UI hierarchy using the Flex containers
Figure 6 UI hierarchy using the relative layout

Statistical Analysis

In different layouts, the number of components and nesting layers required for the same UI effect are different. The following table shows the comparison.

Table 1 Comparison of numbers in different layouts
  

Components

Nesting Layers

Flex container

15

6

Relative layout

9

3

Use the same data records for the test, and record the response latency from when the previous page is touched to when the message box list is rendered. The following table lists the comparison results.

Table 2 Response duration of the list page in different layouts
  

256 Data Records

512 Data Records

1,024 Data Records

Flex container

308 ms

570 ms

1096 ms

Relative layout

249 ms

499 ms

986 ms

Improvement ratio

19.2%

12.5%

10.0%

According to the final statistics:

In actual development, simplifying the layout structure and related elements (including child elements and their parent containers) will improve the response speed of the UI.

[h2]Concurrency Optimization

The following example shows how to add an address. When the Select button is touched, the app switches to the target page of the selected city. During the switchover, the data of nationwide cities is loaded, sorted by the first character, and then updated to the new page list.

In practice, you may implement this functionality in synchronous serial mode. After a button is touched, the page is initialized, data is loaded to the memory, and the entire UI view is rendered.

When about 1,000 data records are loaded in the City page, the response speed is ideal.

When about 2,000 data records are loaded in the District page, the response speed is acceptable.

However, when over 4,000 data records are loaded in the Town/Street page, the response is delayed.

The loading and sorting of area data consume performance. In this case, the concurrency mechanism can be used for optimization.

Code Implementation

In aboutToAppear() of the target page, use TaskPool to start a subthread to load city data concurrently.

@Concurrent
function computeTask(): string[] {
  let array: string[] = []
  // AppConstant.CITYS is the data to be loaded.
  for (let t of AppConstant.CITYS) {
    array.push(t.trim())
  }
  let collator = new Intl.Collator("zh-CN", { localeMatcher: "lookup", usage: "sort" });
  array.sort((a, b) => collator.compare(a, b))
  return array;
}

@Entry
@Component
struct CityList {
  isAsync: boolean = (this.getUIContext().getRouter().getParams() as Record<string, boolean>)['isAsync'];
  // Interface data
  @State citys: string[] = []
  private listScroller: Scroller = new Scroller();

  aboutToAppear() {
    this.computeTaskAsync(); // Call asynchronous operation function
  }

  // Asynchronous thread
  computeTaskAsync() {
    let task: taskpool.Task = new taskpool.Task(computeTask);
    taskpool.execute(task).then((res) => {
      this.citys = res as string[]
    })
  }

  // ...
}

Statistical Analysis

Use Profiler Time to obtain the response durations for different data volumes. The following table lists the results.

Table 3 Response durations for different data volumes
  

500 Data Records

1,000 Data Records

2,000 Data Records

4,000 Data Records

Serial

49 ms

94 ms

296 ms

780 ms

Concurrent

48 ms

86 ms

140 ms

172 ms

In this scenario, if the data volume is less than 1,000 records, user experience of serial loading is good. However, when the number of data records exceeds 1,000, the response duration increases and user experience deteriorates. Obvious response latency occurs from when the finger is lifted to when the first frame is displayed on the list page.

In this case, the advantage of concurrent asynchronous loading is reflected. The UI main thread can quickly start the target list page, trigger the asynchronous loading and sorting logic threads, and update the obtained result to the list, which improves the overall response speed.

[h2]Reducing the Calling for Database API

The following example shows an accounting app that manages related account items based on a relational database.

When user data is to be queried, data in each row in the account table is read in sequence. To obtain the value of each column, you need to use getColumnIndex("column name") to obtain the column index.

Code before modification:

for (let i = 0; i < count; i++) {
  let tmp: AccountData = {
    id: 0,
    accountType: 0,
    typeText: '',
    amount: 0
  };
  tmp.id = resultSet.getDouble(resultSet.getColumnIndex('id'));
  tmp.accountType = resultSet.getDouble(resultSet.getColumnIndex('accountType'));
  tmp.typeText = resultSet.getString(resultSet.getColumnIndex('typeText'));
  tmp.amount = resultSet.getDouble(resultSet.getColumnIndex('amount'));
  result[i] = tmp;
  resultSet.goToNextRow();
}

If the data table structure is fixed, you can invoke getColumnIndex in advance to reduce calls and instruction time consumption. When getColumnIndex is called in the for loop, the number of calls increases with the number of data rows (count), but the index does not change.

Code after modification:

const idIndex = resultSet.getColumnIndex("id");
const accountTypeIndex = resultSet.getColumnIndex("accountType");
const typeTextIndex = resultSet.getColumnIndex("typeText");
const amountIndex = resultSet.getColumnIndex("amount");
for (let i = 0; i < count; i++) {
  let tmp: AccountData = {
    id: 0,
    accountType: 0,
    typeText: '',
    amount: 0
  };
  tmp.id = resultSet.getDouble(idIndex);
  tmp.accountType = resultSet.getDouble(accountTypeIndex);
  tmp.typeText = resultSet.getString(typeTextIndex);
  tmp.amount = resultSet.getDouble(amountIndex);
  result[i] = tmp;
  resultSet.goToNextRow();
}

Statistical Analysis

Use Profiler Time to obtain the response durations for different data volumes. The following table lists the results.

Table 4 Response durations for different data volumes
  

50 Data Records

500 Data Records

5,000 Data Records

Before modification

72 ms

97 ms

157 ms

After modification

72 ms

92 ms

110 ms

Therefore, when using the database, you need to pay attention to the potential frequency of calling related APIs.

When the number of data records is small, the API call has little impact on the app response. However, as the data volume increases with the use time, the high-frequency call will deteriorate the app performance.

[h2]Postponing Resource Release

In this scenario, the camera resources are released after the camera is used properly. To ensure that an app can effectively manage and reclaim all camera resources when the camera is no longer used, you can stop shooting, stop and release the capture session, close the camera input object, release the preview and camera output objects, and clear camera management objects. However, when await is used in captureSession, cameraInput, previewOutput and cameraOutput of the release method, the camera is closed and released in sequence. As a result, the app response may be delayed and the UI may freeze.

In the following code, the resource release operation is triggered in onPageHide():

let cameraOutput: camera.PreviewOutput;
let cameraInput: camera.CameraInput;
let captureSession: camera.PhotoSession;
let previewOutput: camera.PhotoOutput;

  // The camera page is triggered once every time it is hidden.
  onPageHide() {
    this.releaseCamera();
  }

  // Release resources
  public async releaseCamera() {
    try {
      // Photo mode session class pause
      await captureSession?.stop();
      // Photo mode conversation class release
      await captureSession?.release();
      // The photo input object class is closed.
      await cameraInput?.close();
      // Preview output object class release
      await previewOutput?.release();
      // Photo output object class release
      await cameraOutput?.release();
    } catch (e) {
      hilog.error(0x00, 'release input output error:', JSON.stringify(e));
    }
  }

setTimeout is used to delay operations asynchronously. After 200 ms, release is called to close the camera. To ensure that the app can effectively manage and reclaim all camera resources when the camera is no longer used, you only need to stop shooting and execute the following operations concurrently: stop and release the capture session, close the camera input object, release the preview and camera output objects, and clear camera management objects. By removing await for camera resource release to allow asynchronous concurrent execution, the main thread blocking is reduced, improving app performance and response speed.

let cameraOutput: camera.PreviewOutput;
let cameraInput: camera.CameraInput;
let captureSession: camera.PhotoSession;
let previewOutput: camera.PhotoOutput;


  // The camera page is triggered once every time it is hidden.
  onPageHide() {
    setTimeout(this.releaseCamera, 200);
  }

  // Release resources
  public async releaseCamera() {
    try {
      // Photo mode session class pause
      captureSession?.stop();
      // Photo mode conversation class release
      captureSession?.release();
      // The photo input object class is closed.
      cameraInput?.close();
      // Preview output object class release
      previewOutput?.release();
      // Photo output object class release
      cameraOutput?.release();
    } catch (e) {
      hilog.error(0x00, 'release input output error:', JSON.stringify(e));
    }
  }

Performance Comparison

Table 5 Duration for different release logics

Operation Logic

Duration in Trace Diagram

Description

Direct close and release (before modification)

457.5 ms

The camera is closed and released in onPageHide.

Postponed close and release (after modification)

85.6 ms

setTimeout is used in onPageHide to postpone the close and release operations for 200 ms.

The data records show that properly postponing operations can significantly improve the function execution efficiency. It is an effective method to optimize the performance of camera resource management and close operations, improving the overall user experience.

[h2]Reducing the Pan Distance for Gesture Recognition

n this scenario, a gesture event is added to a component. Before the optimization, the minimum pan distance for triggering the pan gesture event is 100 vp. The code is as follows:

import { hiTraceMeter } from '@kit.PerformanceAnalysisKit'

@Entry
@Component
struct PanGestureExample {
  @State offsetX: number = 0
  @State offsetY: number = 0
  @State positionX: number = 0
  @State positionY: number = 0
  private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Left | PanDirection.Right })

  build() {
    Column() {
      Column() {
        Text('PanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
      }
      .height(200)
      .width(300)
      .padding(20)
      .border({ width: 3 })
      .margin(50)
      .translate({ x: this.offsetX, y: this.offsetY, z: 0 }) // Move with the upper left corner of the component as the coordinate origin.
      // Drag left and right to trigger the gesture event.
      .gesture(
        PanGesture(this.panOption)
          .onActionStart((event: GestureEvent) => {
            console.info('Pan start')
            hiTraceMeter.startTrace("PanGesture", 1)
          })
          .onActionUpdate((event: GestureEvent) => {
            if (event) {
              this.offsetX = this.positionX + event.offsetX
              this.offsetY = this.positionY + event.offsetY
            }
          })
          .onActionEnd(() => {
            this.positionX = this.offsetX
            this.positionY = this.offsetY
            console.info('Pan end')
            hiTraceMeter.finishTrace("PanGesture", 1)
          })
      )

      Button('Modify PanGesture trigger condition')
        .onClick(() => {
          this.panOption.setDistance(100)
        })
    }
  }
}

Use Profiler to analyze the trace diagram. The trace process starts from DispatchTouchEvent (type = 0, indicating that the finger touches the screen) on the app side, and ends with PanGesture (event response), which takes 145.1 ms.

The log shows the duration from the time when the app receives TouchDown event to the time when the pan gesture is recognized, which takes 127 ms. Note: The performance data records in log information and trace diagram are different because they are obtained at different time. The provided values are for reference only.

For this component, the pan gesture recognition distance can be adjusted to a more appropriate value. After the optimization, the minimum pan distance for triggering the pan gesture event is 4 vp. The code is as follows:

Button('Modify PanGesture trigger condition')
  .onClick(() => {
    this.panOption.setDistance(4)
  })

Use Profiler to analyze the trace diagram. The duration is 38.4 ms.

The log shows the duration is 42 ms.

Performance Comparison

Table 6 Duration for pan gesture recognition at different distances

Pan Distance

Duration in Trace Diagram

Duration in log

Description

Minimum pan distance: 100 vp (before modification)

145.1 ms

127 ms

If the minimum pan distance is long, users may fail to swipe and the response latency may be long, which will deteriorate performance.

Minimum pan distance: 4 vp (after modification)

38.4 ms

42 ms

Setting a proper pan distance can optimize performance.

The data shows that properly reducing the pan distance can significantly improve execution efficiency, reduce response latency, and improve the overall user experience. The conclusion is drawn based on the comparison between a larger pan distance and a smaller pan distance. If the pan distance is too small, misoperations may occur. You can set the distance based on the actual app scenario.

[h2]Transition Animation Scenario

The following example uses different coherent animations to enable users to experience quick response during operations.

Scenario: After a user touches an item in the message box list, the app switches to the profile page. In this process, three animations are used for the transition:

Figure 7 Scenario example

Implementation

The combination of router, sharedTransition, and animateTo() is used. The procedure is as follows:

  1. Set the pageTransition() parameters on two pages, and add router redirection to the avatar touch event on the list page to implement the transition animation effect from the list page to the profile page.
  2. Add the sharedTransition property to the avatar component Image of the two pages and assign the same ID for unique matching. Add related parameters such as the animation time of the shared element to implement the animation effect of moving the avatar from the list page to the profile page.
  3. Implement a skeleton component based on the layout style of the profile page content, and use animateTo() to add a repeated fade-in and fade-out animation to the skeleton component. Then, display the animation when the profile page component executes onAppear(), and hide the animation element after the page content is displayed.

Core Code

Transition animation settings:

// page A Transition animation settings
pageTransition() {
  PageTransitionEnter({ type: RouteType.None, duration: 400 })
    .slide(SlideEffect.Left)
  PageTransitionExit({ type: RouteType.None, duration: 400 })
    .slide(SlideEffect.Left)
}

Animation settings for shared elements on the list page:

// Use the avatar as a shared element in the list and specify the id as sharedImage+this.itemData.id
Image(this.itemData.avatar)
  .height('40vp')
  .width('40vp')
  .borderRadius(8)
  .sharedTransition('sharedImage' + this.itemData.id, { duration: 500, curve: Curve.FastOutSlowIn, delay: 0 })

Animation settings for shared elements on the profile page:

// The personal page sharing element needs to be the same as the previous page id.
Image(this.itemData.avatar)
  .size({
    width: $r('app.float.user_image_size'),
    height: $r('app.float.user_image_size')
  })// .borderRadius($r('app.float.user_image_border_radius'))
  .borderRadius(8)
  .margin({ bottom: $r('app.float.user_image_padding'), top: $r('app.float.user_image_padding') })
  .sharedTransition('sharedImage' + this.itemData.id,
    { duration: 500, curve: Curve.FastOutSlowIn, delay: 0 })

Implementation of the skeleton screen:

// Skeleton diagram, presenting skeleton animation in a fading way.
startAnimation(): void {
  this.getUIContext().animateTo(CommonConstants.SKELETON_ANIMATION, () => {
    this.listOpacity = CommonConstants.HALF_OPACITY;
  });
}

// Skeletal diagram layout
build() {
  Row() {
    List({ space: Constants.RESOURCE_LIST_SPACE }) {
      ForEach(SkeletonData, (item: SkeType) => {
        ListItem() {
          ArticleSkeletonView({ isMine: item.isMine, isFeed: item.isFeed })
        }
      })
    }
    .padding({
      left: '12vp',
      right: '12vp'
    })
    .lanes(1)
    .layoutWeight(1)
    .scrollBar(BarState.Off)

    Row()
      .layoutWeight(0)
      .backgroundColor($r('app.color.skeleton_color_medium'))
  }
  .width('100%')
  .opacity(this.listOpacity)
  .onAppear(() => {
    this.startAnimation();
  })
}

[h2]Animation Latency Scenario

Page transition animation is crucial to improving user experience. If animation latency is excessive, it significantly increases the touch completion latency, because prolonging the time users must wait before they can interact with the app. In particular, prolonged animation latency is often attributed to an excessively long animation duration.

Common duration parameters of the page transition animation are as follows:

  1. animationDuration: used to set the switching animation duration of TabContent of the Tabs component.
  2. duration: used to set the switching animation duration of the child components of the Swiper component.
  3. duration: a field in the PageTransitionOptions object, which is used to set the duration of pageTransition.

When the Tabs component is used for switching a page, the value of the animationDuration property is 300 ms by default if BottomTabBarStyle is not set. If the value is large, the completion latency increases accordingly. Next, set the value to 100 ms and 1000 ms to explore the impact of the animationDuration property on the completion latency.

Experiment 1: Set the value of animationDuration to 100, in millisecond.

@Entry
@Component
struct TabsPositiveExample {
  @State currentIndex: number = 0;
  private controller: TabsController = new TabsController();
  private list: string[] = ['green', 'blue', 'yellow', 'pink'];

  @Builder
  customContent(color: Color) {
    Column()
      .width('100%')
      .height('100%')
      .backgroundColor(color)
  }

  build() {
    Column() {
      Row({ space: 10 }) {
        ForEach(this.list, (item: string, index: number) => {
          Text(item)
            .textAlign(TextAlign.Center)
            .fontSize(16)
            .height(32)
            .layoutWeight(1)
            .fontColor(this.currentIndex === index ? Color.White : Color.Black)
            .backgroundColor(this.currentIndex === index ? Color.Blue : '#f2f2f2')
            .borderRadius(16)
            .onClick(() => {
              this.currentIndex = index;
              this.controller.changeIndex(index);
            })
        }, (item: string, index: number) => JSON.stringify(item) + index)
      }
      .margin(10)

      Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
        TabContent() {
          this.customContent(Color.Green)
        }

        TabContent() {
          this.customContent(Color.Blue)
        }

        TabContent() {
          this.customContent(Color.Yellow)
        }

        TabContent() {
          this.customContent(Color.Pink)
        }
      }
      .animationDuration(100)
      .layoutWeight(1)
      .barHeight(0)
      .scrollable(false)
    }
    .width('100%')
  }
}

Experiment 2: Set the value of animationDuration to 1000, in millisecond.
@Entry
@Component
struct TabsNegativeExample {
  // ...
  private controller: TabsController = new TabsController();

  // ...

  build() {
    Column() {
      // ...

      Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
        // ...

      }
      .barHeight(0)
      .layoutWeight(1)
      .animationDuration(1000)
      .scrollable(false)
    }
    .width('100%')
  }
}

Table 7 Running result

animationDuration: 100 (ms)

animationDuration: 1000 (ms)

Table 8 Completion latency for different animationDuration

animationDuration

Completion Latency

100 ms

99 ms 39 μs

1000 ms

1s 7 ms 693 μs

The value of the animationDuration property is reduced, which shortens the completion latency for switching the Tabs component. If BottomTabBarStyle is not set, the animation duration is 300 ms by default. You can reduce the animation duration as required to improve app performance.