Android performance optimization - startup optimization

The startup speed of an App is the user’s first experience. There is an eight-second rule on the Internet. If a user waits for eight seconds before the App opens, 70% of users will stop waiting.

 1. Start classification

Official App startup time 

  • Cold start

         The most time-consuming, measurement standard

  • Hot Start

         fastest. Backstage~Frontstage

  • Warm start

         Faster. It will only repeat the life cycle of the activity, but not the creation of the process and the creation and life cycle of the Application.

cold start process

  1. User clicks 
  2. Trigger IPC operation
  3. Process.start process creation
  4. ActivityThread is the entrance to each separate process. There will be a main method to create the message loop and handler.
  5. bindApplication creates Application through reflection and calls the application's life cycle
  6. Activity life cycle LifeCycle 
  7. ViewRootImpl starts the real interface drawing

Before cold start (this process cannot be intervened)

  • Start App 
  • Load a blank Window 
  • Create process

Subsequent tasks

  • CreateApplication 
  • Start the main thread
  • CreateMainActivity 
  • Load layout
  • layout screen
  • First frame drawn

Optimize
        the life cycle of Application and Activity

2. How to measure startup time

adb command mode

        adb shell am start -W packagename/首屏Activity 

    Features:

  • Easy to use offline but cannot be brought online
  • Non-strict, precise time

The manual marking method
        buries points when it starts and buries points when it starts and ends. The difference between the two
     features:       

         Accurate, can be brought online, recommended for use

     Avoid misunderstandings

  • The starting point of the startup time is in the attachBaseContext in the application 
  • The end position of the start time adopts the first display of the feed.
  • addOnDrawListener requires API 16

ThisTime The time taken to start the last Activity
TotalTime The time taken to start all activities
WaitTime The total time taken to start the AMS Activity

3. Start the tools used for optimization

 traceview,systrace 

  • Both tools complement each other
  • Correctly understand tools and choose appropriate tools for different scenarios

traceview

  • advantage
    •  Graphical form, showing code execution time, call stack information, etc.
    • Comprehensive information, including all thread information
  •  Usage

      Debug.startMethodTracing("file name"); the default size is 8M. If you want a larger size, pass the parameter bufferSize. 
      Debug.stopMethodTracing()
      will generate a file at the end of the sd card: Android/data/packagename/files

There is a Devices File Explorer on the right side of Android Studio, which can easily open the files of the mobile phone system.
After adding the opening and closing code, then run it, refresh it under the storage location, and a set file name .trace file will be generated.

  • How to analyze
    • The upper left is the time range accurately specified through the code. There is a time in the lower left corner, which is not particularly important.
    • The lower left is thread information. You can see the total number of threads and what each thread did at a specific time. 

There are four tabs on the right 

  • Top Down

total: total time

self :

children:

For example: Function A is called, the overall time is total, a line of code is called in function A, and then function B is executed. Its selfTime is the time when a line of code is executed, and childrenTime is the time when function B is executed. The sum of selfTime and childrenTime Must be equal to totalTime

Function call list, click the corresponding jump to souse to jump into the detailed code

ThreadTime will definitely become less, the time the CPU executes
Wall Clock Time The code occurs on this thread, the actual execution time

  • Call chat 

Each row shows the time period of the function call, and the vertical method is called.
The color of the system API call is orange,
the application's own function call is green, and
the third-party API call is blue.

  • Flame chat flame graph

Inverted call graph, which collects the same call sequence

  • Bottom up

Who called me is the opposite of Top down

Summary:
        The runtime overhead is serious and the whole thing will be slowed down. This tool is too powerful and will capture all the execution functions of all threads and the order
        may bias the optimization direction. The benefits of
        traceview and cpu profiler 
                traceview can be buried in the code. Use cpu profiler analysis
                It is almost impossible to simply use cpu profiler to capture the precise startup location.

 systrace

Combine Android kernel data to generate html report
Python script

  • Usage

• python systrace.py -t 10 [other-options] [categories]

  • Official documentation:

https://developer.android.com/studio/command-line/systrace#command_options

  • Use Cases

python /Users/Liuzhao.Future/Library/Android/sdk/platform-tools/ systrace/systrace.py -b 32768 -t 5 -a com.optimize.performance -o performance. html sched gf view wm am app

  • used in code

Open: TraceCompat.beginSection(“apponCreate”)
End: TraceCompat.endSection 

  • Analyze html files

The number of CPU cores is related to different mobile phones. Some mobile phone manufacturers give you 8 cores. Some mobile phones have 8 cores, but only 4 cores are used for you.

  • Summarize:
    • Lightweight, low overhead, just do whatever you want to do
    • Intuitively reflects CPU utilization

cpuTime and wallTime

  • wallTime is the time when the code is executed
  • cpuTime is the time the code consumes the CPU (key indicator)

Example: Why do the two have different
        lock conflicts? For example, a thread needs to acquire lock A for execution, but lock A is held by other threads and has not been released. However, this thread is lightweight and only takes up a little time of the CPU. So at this time, cpuTime will be very short, and wallTime will be very long.

4. How to elegantly obtain CPU time consumption

Need to know which method is taking up the most time

  • Conventional method: manual burying points
    • Very invasive
    • Heavy workload
  • AOP method: Aspect Oriented Programming, aspect-oriented programming
    • Unified handling of the same type of problems
    • Add code without intrusion

Aspect use

  • classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.0'
  • implementation 'org.aspectjaspectjrt:1.8.+'
  • apply plugin: 'android-aspectix'

introduce

  • Join Points
    • The execution point when the program is running can be used as a place for aspects
    • function call, execution
    • Get and set variables
    • Class initialization
  • PointCut
    • JoinPoints with conditions
  • Advice
    • A kind of Hook, where the code is to be inserted
    • Before: Executed before PointCut
    • After: Executed after PointCut
    • Around: Execute separately before and after Pointcut
  • Introduction to grammar
    //Before:Advice,具体插入位置
    //execution :处理Join Point的类型
    //(* android.app.Activity.on**(.)):匹配规则
    @Before("execution(* android.app.Activity.on** (.))") 
    public void onActivityCalled (JoinPoint joinPoint) thr
    ows Throwable {
        ……
    }
  • Use Cases
@Aspect
public class Performanceaop{

    Around("call(*com.optimize.performance.PerformanceApp.**(..))") 
    public void getTime(ProceedingJoinPointjoinPoint){
        Signature signature=joinPoint.getSignature(); 
        String name=signaturetoShortString(); 
        long time=System.currentTimeMillis(); 
        try {
            joinPoint.proceed();
        } catch(Throwable throwable){
            throwable.printStackTrace();
        }
        LogUtils.i(msg:name+" cost "+(System.currentTimeMillis() - time));
    }
}
  • advantage
    • Non-invasive
    • Easy to modify

5. Asynchronous optimization

  • General asynchronous optimization: Using thread pools for asynchronous optimization
  • Launcher (the optimal solution for asynchronous startup optimization)

Regular asynchronous mode

Things to note about conventional asynchronous methods:

  • Not all code can be directly asynchronous
  1. Does not meet asynchronous requirements: some tasks must be executed in the main thread
  2. It needs to be completed at a certain stage. Asynchronous tasks are used in the splash interface. When executing the interface, some codes must be completed at a certain stage before the asynchronous task is completed. The solution: CountDownLatch is equivalent to adding a lock.
  3. Distinguish between CPU-intensive and IO-intensive tasks

Pain points of conventional asynchronous solutions:

  • The code is not elegant enough
  • The scene is difficult to handle (dependency), end a task within a specific time
  • High maintenance costs

Launcher mode

Core idea:
     Make full use of CPU multi-cores and automatically sort out the task sequence.
Launcher process:

  • The code is Task-oriented and the startup logic is abstracted into Task 
  • Generate a directed acyclic graph based on the dependencies of all tasks
  • Multi-threads are executed sequentially according to the sorted priority.

6. Delayed initialization

  • General solution: handler.postDelay 
  • Better solution: Initialize delayed tasks in batches

Problems with conventional solutions:

  • The timing is difficult to control
  • Causing feed lag

Advantages of the better solution: Taking advantage of the IdleHandler feature, idle execution

  • Execution time is clear
  • Alleviate feed lag

7. Summary: launch the general policy of optimization

  • Asynchronous, delayed, lazy loading
  • Combining technology and business

8. Precautions

  • Convergence startup code modification permissions
  • Modifying the startup code in conjunction with Ci requires a Review or notification

9. Other options

  • Load SharedPreferences ahead of time 

        Load before multidex, make full use of this stage and the CPU 
        overwrites getApplicationContext and returns this

  • Do not start child processes during startup

        Child processes will share CPU resources, causing the main process CPU to be strained.
         Pay attention to the startup sequence. App onCreate is preceded by ContentProvider. 

  • Class loading optimization, asynchronous class loading in advance
  • Suppress GC during startup phase 
  • CPU frequency lock

Guess you like

Origin blog.csdn.net/weixin_42277946/article/details/131808262