Android启动优化--AOP获取方法耗时

启动优化--AOP获取方法耗时

AOP 的意思是面向切面编程,详见 Spring 中的 AOP,是一个意思。

背景

需要知道启动阶段各个方法耗时情况,常规操作是通过手动埋点的方式,这个方式代码的侵入性强,工作量大。

AOP介绍

Aspect Oriented Programming , 面向切面编程,优点如下。

(1)针对同一类问题的统一处理

(2)无侵入添加代码

AspectJ 的使用

这个是用来辅助实现AOP的。

(1)在项目的根目录下的 build.gradle 下面添加  classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.0'  。如:

(2)在 app 目录下的 build.gradle 文件中,在 dependencies 添加  implementation 'org.aspectj:aspectjrt:1.8.+' 。

(3)在 app 目录下的 build.gradle 文件中,在该文件的最上面添加  apply plugin: 'android-aspectjx' 。如下:

相关概念:

@Aspect
public class PerformanceAop {

    @Around("call(* com.optimize.performance.PerformanceApp.**(..))")
    public void getTime(ProceedingJoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        String name = signature.toShortString();
        long time = System.currentTimeMillis();
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        LogUtils.i(name + " cost " + (System.currentTimeMillis() - time));
    }
}

结果如下:

优点:

(1)代码无侵入性,

(2)方便修改;

总结

(1)优雅获取方法耗时的方式;

(2)AOP的理解和使用

猜你喜欢

转载自blog.csdn.net/gs344937933/article/details/89742189