HarmonyOS 应用性能优化 ArkUI 实战:不引图表库 —— 停车费用页手写的五柱趋势图与地点消费榜

前言

停车费用页是深灰主题的统计页:顶部深灰渐变月度卡(¥286 主金额)、中部手写五柱月度趋势图(4 月 220 / 5 月 260 / 6 月 310 / 7 月 245 / 8 月 286 元,深灰柱 + 柱顶金额 + 月份标签)、底部地点消费榜(公司车库 20 次 ¥400 / 万达广场 8 次 ¥96 / 市医院 3 次 ¥24)。手写图表不引库是可行的,但性能责任全落在自己身上。本篇聚焦两个角度:一是五柱趋势图的绘制指令复用——柱子的尺寸计算、颜色、圆角这些"绘制参数"在数据变更期一次物化为绘制指令数组,渲染期逐柱读取,滚动与刷新都不重算比例;二是地点消费榜的增量排序——榜单按消费额排序,新增一笔停车记录时只涉及"一个地点的合计值变化",用插入式更新把 O(n log n) 的全量重排降为 O(n) 以内的单元素归位。两处优化的共同点是把"比例与次序"这类结构性结论提前算好,让渲染期保持纯粹。代码基于 API 12,@kit 导入,自包含可编译。

一、问题背景

页面四区:单行标题头、深灰渐变月度卡、五柱趋势图卡、地点消费列表(44×44 圆形浅灰底图标 + 地点名 + 次数 + 深灰金额)。数据口径上,五柱合计与月度卡金额对账、榜单金额与首页费用合计对账。

原始实现的性能问题:

第一,柱高比例渲染期重算。每根柱子的高度表达式内联 val * 110 / maxVal(),maxVal 又是每次现场遍历——五根柱子五次遍历求同一个最大值,且每次页面刷新都重来。

第二,柱子样式逐次构建。柱宽、顶部圆角、颜色对所有柱子恒定,却写在每根柱子的渲染代码里重复描述;数据不变时这些绘制参数本可以只算一次。

第三,榜单全量重排。每新增一条停车记录,榜单对全部地点重新 sort。地点数不多时无感,但连锁场景(几十个停车场、高频录入)下,每次录入都全量排序是纯浪费——一次录入只会改变一个地点的合计值。

费用页整体布局

上图为费用页整体:月度卡、趋势图、消费榜纵向排布。统计页的渲染密度高,渲染路径上任何重复计算都会被放大。

二、原理分析

原理一:绘制指令物化。 柱状图渲染期真正需要的只是"每根柱的最终高度 vp 值 + 恒定样式"。在数据变更期执行一次归一化:求最大值、算出每柱高度、连同恒定的柱宽/圆角/颜色打包成绘制指令数组。渲染期 ForEach 逐项读指令,不做任何算术。这与前述"预计算下推"同源,但强调"打包"——指令数组是渲染的唯一消费入口,谁也不允许绕过它直接碰原始数值。

原理二:绘制指令的复用边界。 指令数组按"数据版本"缓存:数据没变,指令数组原样复用(引用相等),框架对未变化子树的最小化更新直接跳过;数据变了,指令数组整体重建(柱数固定时重建成本是 O(n) 一次)。复用的判定锚点是数据版本号,不是逐字段比较。

原理三:增量排序的插入归位。 榜单是有序数组,维护有序性不必每次全排。新记录到达时:先在聚合表里更新该地点的合计(O(1)),然后把该地点从数组中取出、按新合计值在剩余有序数组里二分定位、插回(O(log n) 定位 + O(n) 移位)。只有被更新元素的相对位置可能变,其余元素的次序完全不动——ForEach 的键值稳定,UI 只移动一个节点。删除记录同理反向。全量重排只在数据导入、清空这类批量事件发生。

原理四:榜单键值与节点移动。 增量排序配合稳定键值(地点名/id),位置变化被框架识别为节点移动而非销毁重建,这正是增量排序的 UI 端收益来源;若键值里掺入排名序号,每次归位都会引发整列表重建,优化即失效——排序策略与键值策略必须配套设计。

三、代码实现

以下代码块属同一 .ets 文件,按顺序拼接,可整体替换原页面文件编译运行。

第一段:绘制指令物化与榜单增量排序器。

interface MonthPoint {
  label: string;
  value: number;
}

// 柱子的绘制指令:渲染期只读不算
interface BarSpec {
  heightVp: number;
  amountLabel: string;
}

interface PlaceAgg {
  place: string;
  count: number;
  total: number;
}

const BAR_MAX_HEIGHT: number = 110;
const BAR_WIDTH: number = 24;
const BAR_TOP_RADIUS: number = 4;

class Theme {
  static readonly bg: string = '#F2F5FB';
  static readonly card: string = '#FFFFFF';
  static readonly cardSoft: string = '#F4F6FB';
  static readonly stroke: string = '#EAEEF6';
  static readonly text: string = '#1C2333';
  static readonly textSub: string = '#5A6483';
  static readonly textDim: string = '#9AA3BC';
  static readonly dark: string = '#2D3436';
  static readonly darkAccent: string = '#636E72';
  static readonly pad: number = 16;
}

// 物化绘制指令:一次遍历求最大值并归一化
function buildBarSpecs(months: MonthPoint[]): BarSpec[] {
  let max = 1;
  for (let i = 0; i < months.length; i++) {
    if (months[i].value > max) {
      max = months[i].value;
    }
  }
  const specs: BarSpec[] = [];
  for (let i = 0; i < months.length; i++) {
    specs.push({
      heightVp: months[i].value * BAR_MAX_HEIGHT / max,
      amountLabel: '¥' + months[i].value.toString()
    });
  }
  return specs;
}

// 榜单增量排序器:单元素归位代替全量重排
class PlaceRanker {
  private list: PlaceAgg[] = [];

  seed(agg: PlaceAgg[]): void {
    this.list = agg.slice();
    this.list.sort((a: PlaceAgg, b: PlaceAgg) => {
      return b.total - a.total;
    });
  }

  getList(): PlaceAgg[] {
    return this.list;
  }

  // 新增一笔:目标地点合计增加后单元素归位
  addBill(place: string, cost: number): void {
    let target: PlaceAgg | null = null;
    let idx = -1;
    for (let i = 0; i < this.list.length; i++) {
      if (this.list[i].place === place) {
        target = this.list[i];
        idx = i;
        break;
      }
    }
    if (target === null) {
      target = { place: place, count: 0, total: 0 };
      this.list.push(target);
      idx = this.list.length - 1;
    }
    target.count += 1;
    target.total += cost;
    this.relocate(Math.max(idx, 0));
  }

  private relocate(from: number): void {
    const item = this.list[from];
    this.list.splice(from, 1);
    let pos = this.list.length;
    for (let i = 0; i < this.list.length; i++) {
      if (item.total > this.list[i].total) {
        pos = i;
        break;
      }
    }
    this.list.splice(pos, 0, item);
  }
}

第二段:费用页组件——柱状图读绘制指令、榜单走增量排序与稳定键值。

@Entry
@Component
struct ParkingCost {
  @State private bars: BarSpec[] = buildBarSpecs([
    { label: '4月', value: 220 }, { label: '5月', value: 260 }, { label: '6月', value: 310 },
    { label: '7月', value: 245 }, { label: '8月', value: 286 }
  ]);
  @State private months: MonthPoint[] = [
    { label: '4月', value: 220 }, { label: '5月', value: 260 }, { label: '6月', value: 310 },
    { label: '7月', value: 245 }, { label: '8月', value: 286 }
  ];
  private ranker: PlaceRanker = new PlaceRanker();
  @State private places: PlaceAgg[] = [];
  @State private monthTotal: string = '286';

  aboutToAppear(): void {
    this.ranker.seed([
      { place: '公司车库', count: 20, total: 400 },
      { place: '万达广场', count: 8, total: 96 },
      { place: '市医院', count: 3, total: 24 }
    ]);
    this.places = this.ranker.getList();
  }

  private simulateNewBill(place: string, cost: number): void {
    this.ranker.addBill(place, cost);
    this.places = this.ranker.getList();
  }

  @Builder
  SummaryCard() {
    Column({ space: 8 }) {
      Text('¥' + this.monthTotal).fontSize(36).fontWeight(FontWeight.Bold).fontColor('#FFFFFF')
      Text('8月停车总费用').fontSize(13).fontColor('#FFFFFF').opacity(0.9)
    }
    .width('100%').padding(24)
    .linearGradient({ angle: 135, colors: [[Theme.dark, 0.0], [Theme.darkAccent, 1.0]] })
  }

  @Builder
  BarChart() {
    Column({ space: 14 }) {
      Text('月度费用趋势').fontSize(14).fontWeight(FontWeight.Bold).fontColor(Theme.text).width('100%')
      Row() {
        ForEach(this.months, (m: MonthPoint, idx: number) => {
          Column({ space: 6 }) {
            Text(this.bars[idx].amountLabel).fontSize(9).fontColor(Theme.textDim)
            Column()
              .width(BAR_WIDTH).height(this.bars[idx].heightVp)
              .backgroundColor(Theme.dark)
              .borderRadius({ topLeft: BAR_TOP_RADIUS, topRight: BAR_TOP_RADIUS })
            Text(m.label).fontSize(10).fontColor(Theme.textSub)
          }.layoutWeight(1).justifyContent(FlexAlign.End)
        }, (m: MonthPoint) => m.label)
      }.width('100%').height(160).alignItems(VerticalAlign.Bottom)
    }
    .width('100%').padding(16).backgroundColor(Theme.card).borderRadius(20)
    .border({ width: 1, color: Theme.stroke })
  }

  @Builder
  PlaceList() {
    Column({ space: 12 }) {
      Text('地点消费').fontSize(14).fontWeight(FontWeight.Bold).fontColor(Theme.text).width('100%')
      ForEach(this.places, (p: PlaceAgg, idx: number) => {
        Row({ space: 12 }) {
          Text((idx + 1).toString()).fontSize(13).fontWeight(FontWeight.Bold)
            .fontColor(Theme.darkAccent).width(20)
          Row() { Text(p.place.substring(0, 1)).fontSize(18).fontColor('#FFFFFF') }
          .width(44).height(44).backgroundColor(Theme.darkAccent).borderRadius(22)
          .justifyContent(FlexAlign.Center)
          Column({ space: 4 }) {
            Text(p.place).fontSize(14).fontWeight(FontWeight.Medium).fontColor(Theme.text)
            Text(p.count.toString() + ' 次').fontSize(11).fontColor(Theme.textDim)
          }.alignItems(HorizontalAlign.Start).layoutWeight(1)
          Text('¥' + p.total.toString()).fontSize(14).fontWeight(FontWeight.Bold).fontColor(Theme.dark)
        }
        .width('100%').padding(10).backgroundColor(Theme.card).borderRadius(12)
        .border({ width: 1, color: Theme.stroke })
      }, (p: PlaceAgg) => p.place)
    }
    .width('100%').padding(16).backgroundColor(Theme.card).borderRadius(20)
    .border({ width: 1, color: Theme.stroke })
  }

  build() {
    Column() {
      Row() {
        Text('费用统计').fontSize(20).fontWeight(FontWeight.Bold).fontColor(Theme.text)
      }
      .width('100%').height(76).padding({ top: 20, left: Theme.pad, right: Theme.pad })
      .backgroundColor(Theme.card).alignItems(VerticalAlign.Bottom)
      Scroll() {
        Column({ space: 14 }) {
          this.SummaryCard()
          this.BarChart()
          this.PlaceList()
          Button('模拟新增一笔停车(万达广场 ¥12)').fontSize(12)
            .fontColor('#FFFFFF').backgroundColor(Theme.darkAccent)
            .height(36).borderRadius(10)
            .onClick(() => { this.simulateNewBill('万达广场', 12); })
        }
        .width('100%')
        .padding({ left: Theme.pad, right: Theme.pad, top: 14, bottom: 40 })
      }
      .layoutWeight(1).scrollBar(BarState.Off).align(Alignment.Top)
    }
    .width('100%').height('100%').backgroundColor(Theme.bg)
  }
}

月度费用趋势柱状图

五柱趋势图的最终效果如上图。柱高全部来自 bars 指令数组,渲染表达式里没有一处除法——比例已在数据变更期算定。

地点消费统计列表如上图,名次次序由增量归位维护。

地点消费统计列表

四、性能对比与验证方法

测量条件如下表:

项目条件
设备档位中端真机(8GB RAM)+ 低端真机(4GB RAM)
系统/SDK 版本HarmonyOS NEXT API 12,DevEco Studio 5.0
数据规模5 柱固定;榜单 3 / 30 / 100 个地点三组,每组连续录入 200 笔
采样次数录入 200 笔耗时取中位数;页面刷新 build 10 次取中位数
打点方式buildBarSpecs 与 addBill 打点;ForEach 节点重建数用组件树日志

以下为示例实测值,非设备基准数据,需在目标机型复测:

指标(100 地点 + 200 笔录入)优化前优化后变化幅度
单笔录入的榜单维护耗时0.9ms(全量 sort)0.1ms(单元素归位)-89%
录入触发的列表节点重建全列表1 个节点移动-98%
页面刷新的柱高计算次数每柱 1 次遍历0 次(指令读取)消除
榜单渲染期算术运算每行 2 次0 次消除

验证方法:增量正确性用"200 笔随机录入后,增量榜单与 seed+全量 sort 的结果逐项比对"的断言;节点移动数在 ForEach 键值回调加日志统计;柱高指令复用在数据不变时重复 build,确认 bars 引用未变。反直觉结论:榜单只有 3 个地点时,增量归位比全量 sort 更慢(定位与 splice 的固定开销大于 3 元素排序)——增量排序的收益与地点数正相关,10 个以下直接全排更简单也更稳;本页演示数据恰好是 3 个,工程上应设阈值降级。

费用页顶部月度卡如上图,金额与五柱合计同源对账。

费用页顶部月度卡

五、优化建议与工程化落地

第一,buildBarSpecs 与 PlaceRanker 收进图表/榜单工具层。柱状图组件与消费榜组件对外只暴露"喂数据、拿指令",内部归一化与排序策略不泄漏。

第二,增量排序设降级阈值。地点数低于 10 时自动退化为全量 sort,代码里一条 if 即可——不要为了架构一致在小数据上坚持增量。

第三,榜单键值纪律写成团队约定。稳定键值(业务 id)+ 禁止掺入序号/排名,配 code review 检查项;键值策略与排序策略的配套关系写进组件文档。

第四,月度卡与五柱合计的对账断言。286 应等于五柱里 8 月柱的值、也应等于榜单合计的本月切面,三处对账写成单元测试,防止后续改口径时页面间数字漂移。

第五,深灰主题的对比度核查。深灰柱压在白卡上、深灰金额压在白底上,对比度都在安全区;但榜单序号用 darkAccent 时要验证小字号下的可读性,必要时加深。

本篇配图。

六、总结:HarmonyOS 应用性能优化的指令与次序

费用页的两组优化各自回答一个结构性问题:图表的"比例"在什么时候算——答案是在数据变更期一次算成绘制指令,渲染期只描不算;榜单的"次序"在什么时候动——答案是单笔变更只让一个元素归位,其余次序原封不动。手写图表的责任感体现在把图表库藏在内部的事(归一化、指令缓存)明明白白做出来,增量排序的敏锐体现在看清"一次录入只动一个地点"这个业务事实。统计页的性能上限,取决于结构性能否提前于渲染确定——指令先于像素,次序先于列表。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐