本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
一、渲染性能优化
1. 组件树优化
问题:过深的组件嵌套会导致渲染性能下降
解决方案:
// 不推荐 - 嵌套过深
Column() {
Row() {
Column() {
Row() {
Text("多层嵌套")
}
}
}
}
// 推荐 - 扁平化结构
Column() {
Text("扁平结构").margin({top: 10})
Text("减少嵌套").margin({top: 10})
}
优化技巧:
- 使用
if/else替代visibility属性控制显示 - 复杂界面使用
LazyForEach延迟加载 - 避免在
build函数中进行耗时操作
2. 列表性能优化
长列表优化方案:
// 使用LazyForEach优化长列表
LazyForEach(this.dataArray, (item: DataItem) => {
ListItem() {
Text(item.name).fontSize(16)
}
}, (item) => item.id.toString())
关键参数:
- 设置
cachedCount预加载数量(通常3-5) - 使用
listDirection控制滚动方向 - 为列表项设置固定高度
二、内存优化
1. 资源管理
图片资源优化:
Image($r('app.media.large_img'))
.width(200)
.height(200)
.interpolation(ImageInterpolation.High) // 高质量缩放
.objectFit(ImageFit.Contain) // 合适的内容模式
//interpolation(ImageInterpolation.High) 属性通过优化图像缩放算法来平衡画质与内存开销
建议:
- 使用WebP格式替代PNG/JPG
- 按屏幕密度提供多套资源
- 及时释放不再使用的资源
2. 对象复用
对象池技术:
class ObjectPool<T> {
private pool: T[] = [];
get(recycle: () => T): T {
return this.pool.pop() || recycle();
}
release(obj: T) {
this.pool.push(obj);
}
}
// 使用示例
const textPool = new ObjectPool<Text>();
const text = textPool.get(() => new Text());
// 使用完毕后
textPool.release(text);
三、启动速度优化
1. 冷启动优化
关键措施:
- 减少首屏依赖的模块
- 使用
async/await拆分初始化任务 - 预加载关键资源
代码示例:
async aboutToAppear() {
// 非关键任务延迟执行
setTimeout(() => {
this.loadSecondaryData();
}, 500);
// 关键路径优先执行
await this.loadEssentialData();
}
2. 分包加载
配置方法:
// module.json5
{
"module": {
"name": "entry",
"type": "entry",
"deliveryWithInstall": true,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "MainAbility",
"srcEntry": "./ets/mainability/MainAbility.ts",
"label": "$string:MainAbility_label",
"icon": "$media:icon",
"visible": true,
"skills": [
{
"actions": [
"action.system.home"
],
"entities": [
"entity.system.home"
]
}
]
}
]
}
}
分包详细步骤:鸿蒙开发中 分包加载
四、网络性能优化
1. 请求合并
批量请求示例:
async function batchRequests(urls: string[]) {
const promises = urls.map(url => fetch(url));
return await Promise.all(promises);
}
// 使用
const results = await batchRequests([
'api/data1',
'api/data2'
]);
2. 缓存策略
智能缓存实现:
class ApiCache {
private cache = new Map<string, { data: any, expire: number }>();
async get(url: string) {
const cached = this.cache.get(url);
if (cached && cached.expire > Date.now()) {
return cached.data;
}
const freshData = await fetch(url);
this.cache.set(url, {
data: freshData,
expire: Date.now() + 5 * 60 * 1000 // 5分钟缓存
});
return freshData;
}
}
3. 使用HTTP/2多路复用
通过HTTP/2的多路复用特性,可在同一连接上并发多个请求,无需合并逻辑但天然支持高效传输:
import http from '@ohos.net.http';
// 配置HTTP/2客户端
let httpClient = http.createHttp();
httpClient.request("https://api.example.com", {
method: http.RequestMethod.GET,
protocolVersion: http.HttpProtocol.VERSION_2, // 启用HTTP/2
header: { 'Content-Type': 'application/json' }
});
优势:自动复用TCP连接,减少握手开销
4. 手动合并请求(通用方案)
将多个API请求合并为单个后端接口,或通过参数聚合实现:
// 合并用户信息和订单请求
async function fetchCombinedData(userId: string) {
const combinedUrl = `https://api.example.com/combined?user=${userId}&include=orders,profile`;
let response = await httpClient.request(combinedUrl, {
method: http.RequestMethod.GET
});
// 解析返回的聚合数据
const { user, orders } = JSON.parse(response.result);
}
适用场景:需后端支持合并接口
5. 利用OkHttp的批量请求(鸿蒙兼容方案)
通过第三方库(如OkHttp适配)实现请求队列合并:
// 示例:Java侧代码(需通过FFI调用或封装成Native API)
List<Request> requests = Arrays.asList(
new Request.Builder().url("https://api.example.com/user").build(),
new Request.Builder().url("https://api.example.com/orders").build()
);
OkHttpClient client = new OkHttpClient();
List<Response> responses = requests.stream()
.map(request -> client.newCall(request).execute())
.collect(Collectors.toList());
注意:需通过Native层桥接调用。
五、线程优化
1. Worker线程使用
创建Worker:
// worker.ts
import worker from '@ohos.worker';
const workerPort = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
// 处理耗时任务
const result = heavyCalculation(e.data);
workerPort.postMessage(result);
}
// 主线程调用
const worker = new worker.ThreadWorker("ets/workers/worker.ts");
worker.postMessage(inputData);
worker.onmessage = (result) => {
// 处理结果
};
2. 任务优先级
任务调度示例:
import taskpool from '@ohos.taskpool';
@Concurrent
function processData(data: any) {
// 耗时处理
return result;
}
async function runTask() {
const task = new taskpool.Task(processData, inputData);
// 高优先级任务
const result = await taskpool.execute(task, taskpool.Priority.HIGH);
}
六、存储优化
1. 数据库优化
高效查询方案:
1. 直接通过索引,避免全表扫描
2. 在数据库引擎层对结果集按 name 排序,比内存排序更快(尤其数据量大时)
3. 仅返回 前50条数据,减少数据传输量和内存占用
4. 列投影(Projection):只查询 id、name、salary 三列,避免读取无关字段(如大文本或未使用的列)
const predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.equalTo("department", "dev")
.orderByAsc("name")
.limit(50)
.offset(0);
const result = await store.query(predicates, ["id", "name", "salary"]);
其实底层,鸿蒙 RDB 会将查询编译为优化的 SQL 语句
2. 文件IO优化
高效文件操作:
import fs from '@ohos.file.fs';
async function writeLargeFile(path: string, data: any[]) {
const file = await fs.open(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// 分批写入
const BATCH_SIZE = 1024;
for (let i = 0; i < data.length; i += BATCH_SIZE) {
const chunk = data.slice(i, i + BATCH_SIZE);
await fs.write(file.fd, JSON.stringify(chunk));
}
await fs.close(file.fd);
}
七、功耗优化
1. 传感器使用优化
import sensor from '@ohos.sensor';
class SensorManager {
private sensorId: number | null = null;
startAccelerometer() {
this.sensorId = sensor.on(sensor.SensorId.ACCELEROMETER, (data) => {
// 处理数据
}, {
interval: 100000 // 100ms采样间隔
});
}
stop() {
if (this.sensorId) {
sensor.off(this.sensorId);
}
}
}
2. 后台任务管理
合理使用后台任务:
import backgroundTaskManager from '@ohos.backgroundTaskManager';
function startBackgroundTask() {
const delay = 5000; // 5秒后执行
backgroundTaskManager.startBackgroundRunning(
this.context,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER,
delay
).then(() => {
console.log('后台任务已启动');
});
}
八、持续性能监控
1. 性能数据收集
import hiTraceMeter from '@ohos.hiTraceMeter';
function trackPerformance() {
const traceId = hiTraceMeter.startTrace('page_load', 12345);
// 关键业务逻辑
loadPageData();
hiTraceMeter.finishTrace(traceId);
}
2. 内存泄漏检测
对象引用监控:
class LeakDetector {
private weakRefs = new Set<WeakRef<object>>();
track(obj: object) {
this.weakRefs.add(new WeakRef(obj));
}
checkLeaks() {
for (const ref of this.weakRefs) {
if (!ref.deref()) {
console.warn('对象可能已泄漏');
}
}
}
}
通过以上系统化的性能优化措施,可以显著提升应用的运行效率、降低资源消耗,从而提供更流畅的用户体验。建议具体情况选择适合的优化策略,并通过性能分析工具持续监控优化效果。

1184

被折叠的 条评论
为什么被折叠?



