Article / 2026/05/31

性能优化 (十二) 优雅获取方法耗时

性能优化 (十二) 优雅获取方法耗时 的技术笔记。

优雅获取方法耗时

常规方式

  • 背景:需要知道启动阶段所有方法耗时
  • 实现:手动埋点
  • 侵入性强
  • 工作量大

AOP介绍

  • Aspect Oriented Programming, 面向切面编程
  • 针对同一类问题的统一处理
  • 无侵入添加代码

AOP实战

  • AspectJ使用
  1. classpath ‘com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.0’
  2. implementation ‘org.aspectj:aspectjrt:1.8.+’
  3. apply plugin: ‘android-aspectjx’
  • Join Points
  1. 程序运行时的执行点,可以作为切面的地方
  2. 函数调用、执行
  3. 获取、设置变量
  4. 类初始化
  • PointCut
  1. 待条件的JoinPoints
  • Advice
  1. 一种Hook,要插入代码的位置
  2. Before: PointCut之前执行
  3. After: PointCut之后执行
  4. Around: PointCut之前、之后分别执行
  5. 如:
@Before("execution(*android.app.Activity.on**(..))")
public void onActivityCalled(JoinPoint joinpoint) throws Throwable{
...
}
  • 语法介绍
  1. Before: Advice,具体插入的位置
  2. execution: 处理Join Point的类型,call、execution
  3. (* android.app.Activity.on**(..)) : 匹配规则
  4. onActivityCalled: 要插入的代码

Giscus 未启用:请在 src/site.config.ts 中配置 repoId 与 categoryId。