DEV Community

HarmonyOS
HarmonyOS

Posted on

Performant ArkTS Programming: Best Practices for High-Efficiency Code

Read the original article:Performant ArkTS Programming: Best Practices for High-Efficiency Code

image.png

Photo by steffi on Unsplash

Introduction

ArkTS offers developers a powerful, TypeScript-like syntax with optimizations designed for better runtime performance. However, writing performant applications requires more than just using the right framework; it also demands awareness of low-level optimizations.

In this article, we’ll explore real-world performant programming practices for ArkTS. Whether you’re building user interfaces, computing logic, or dealing with data structures, these tips will help you write faster, leaner, and more efficient applications.

Declaration and Expression Best Practices

✅ Use **const** for Invariant Variables

If a variable’s value doesn’t change, define it with const. This allows the engine to optimize memory and access paths more effectively.

const index = 10000; 
Enter fullscreen mode Exit fullscreen mode

🚫 Avoid Mixing Integer and Floating-Point Types

ArkTS distinguishes between integer and floating-point types under the hood. Mixing them can degrade performance due to type re-evaluation.

let num = 1;
num = 1.1; // ⚠️ Don't mix types after initializationCopy
Enter fullscreen mode Exit fullscreen mode

🚫 Avoid Arithmetic Overflow

Arithmetic operations that exceed INT32_MAX or fall below INT32_MIN can push the engine into slower execution paths.

Avoid overflows in operations like +, -, *, **, &, and >>> for performance-sensitive logic.

✅ Extract Constants Outside Loops

Accessing class properties or static values repeatedly inside a loop increases attribute lookup costs. Instead, cache them outside the loop.

const info = Time.info[num - Time.start];
for (let index = 0x8000; index > 0x8; index >>= 1) {
  if ((info & index) !== 0) {
    total++;
  }
}
Enter fullscreen mode Exit fullscreen mode

Function Optimization

✅ Prefer Parameter Passing Over Closures

Closures introduce memory and performance overhead. For hot paths, pass variables directly via function parameters.

function foo(arr: number[]): number {
  return arr[0] + arr[1];
}
Enter fullscreen mode Exit fullscreen mode

🚫 Avoid Optional Parameters in Hot Paths

Optional parameters result in extra undefined checks, which slow down execution.

// Instead of this:
function add(a?: number, b?: number): number | undefined { ... }

// Use this:
function add(a: number = 0, b: number = 0): number {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Array Usage Recommendations

✅ Use **TypedArray** for Numeric Data

When performing arithmetic, TypedArray (like Int8Array, Float32Array) provides better performance than regular Array<number>.

const arr1 = new Int8Array([1, 2, 3]);
const arr2 = new Int8Array([4, 5, 6]);
let result = new Int8Array(3);
Enter fullscreen mode Exit fullscreen mode

🚫 Avoid Sparse Arrays

Sparse arrays (e.g., arr[9999] = 0) are stored as hash tables internally and are much slower to access. Always initialize arrays with contiguous elements when performance matters.

🚫 Avoid Union Arrays and Mixed Types

Combining different types number | string in one array leads to deoptimization. Stick to a single consistent type per array.

let arrInt: number[] = [1, 2, 3];
let arrStr: string[] = ["a", "b"];
Enter fullscreen mode Exit fullscreen mode

Exception Handling

🚫 Avoid Frequent Exceptions

Throwing exceptions often leads to the creation of costly stack frames, which negatively impact performance. Therefore, it is important to avoid frequent exception throwing in performance-critical areas, such as inside for loops.

// Before optimization
function div(a: number, b: number): number {
  if (a <= 0 || b <= 0) {
    throw new Error('Invalid numbers.')
  }
  return a / b
}


function sum(num: number): number {
  let sum = 0
  try {
    for (let t = 1; t < 100; t++) {
      sum += div(t, num)
    }
  } catch (e) {
    console.log(e.message)
  }
  return sum
}

// After optimization
function div(a: number, b: number): number {
  if (a <= 0 || b <= 0) {
    return NaN
  }
  return a / b
}


function sum(num: number): number {
  let sum = 0
  for (let t = 1; t < 100; t++) {
    if (t <= 0 || num <= 0) {
      console.log('Invalid numbers.')
    }
    sum += div(t, num)
  }
  return sum
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Writing performant ArkTS code means minimizing unnecessary type changes, reducing memory usage, avoiding heavy exceptions, and using data types that align with the system.

By integrating these best practices into your development workflow, you’ll not only write faster applications but also improve code maintainability and reliability in performance-sensitive environments.

If you’re developing with ArkTS or exploring HarmonyOS, adopting these small, focused changes can yield massive performance improvements. Happy coding!

References

https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/arkts-high-performance-programming-V5?source=post_page-----fe6f93fc9f04---------------------------------------

https://medium.com/huawei-developers/performant-arkts-programming-best-practices-for-high-efficiency-code-fe6f93fc9f04

Written by Emine Inan

Top comments (0)