Android startup optimization - class preloading

background

Among the various optimizations of Android, one of the unavoidable ones is startup optimization. Most of the optimizations are often related to business, such as delayed loading, preloading of specific resources, etc. Today we will not discuss business related, but only load class optimization from jvm Since it is logically independent and relatively simple to implement.

class loading

Briefly describe the class loading of Android, which refers to loading the corresponding class from the dex package into the method area, and this class object can be used later. This class loading mechanism is also used to derive a plug-in and hot-fix mechanism.

ClassLoader

The parental delegation mechanism of jvm will not be briefly described here;

  1. BootClassLoader loads the Framework class;

  2. PathClassLoader The default ClassLoader is responsible for loading the apk that has been installed in the system (/data/app). Its constructor only allows passing in dexPath and libraryPath (native lib path).

  3. DexClassLoader can load dex packages in different paths without limitation. DexClassLoaders is the basis of plug-in and hot fix. The constructor can pass in dexPath, libraryPath, optimizedDirectory (dex2oat cache path), and the dex2oat operation will generate an ELF file. We will use the optimizedDirectory parameter to optimize the dex of the plugin (AOT).

class loading timing

image.png

How to know which classes are more time-consuming

During the online stage, it was found that many ANRs appeared on Class#findClass. If time-consuming classes can be preloaded in advance on non-UI threads at the right time, the probability of ANRs can also be reduced.

We can use Hook ClassLoader to count which classes are time-consuming offline/online.

/**
 * 统计loadClass耗时
 */
class LogClassLoader(dexPath: String, parent: ClassLoader) : PathClassLoader(dexPath, parent) {

    override fun loadClass(name: String): Class<*> {
        if (name.startsWith("android.") || name.startsWith("java.lang")) {
            return super.loadClass(name)
        }
        val start = System.currentTimeMillis()
        try {
            return super.loadClass(name)
        } finally {
            val cost= System.currentTimeMillis() - start
            val thread = Thread.currentThread().name
            Log.i("loadClass", "load $name thread:$thread cost: $cost")
        }
    }
} 

At the initialization entry, hook classLoader, and finally can count which classes are relatively time-consuming.

fun hook(application: Application) {
    val pathClassLoader = application.classLoader
    try {
        val logClassLoader = LogClassLoader("", pathClassLoader.parent)
        val pathListField = BaseDexClassLoader::class.java.getDeclaredField("pathList")
        pathListField.isAccessible = true
        val pathList = pathListField.get(pathClassLoader)
        pathListField.set(logClassLoader, pathList)

        val parentField = ClassLoader::class.java.getDeclaredField("parent")
        parentField.isAccessible = true
        parentField.set(pathClassLoader, logClassLoader)
    } catch (throwable: Throwable) {
        Log.e("hook", throwable.stackTraceToString())
    }
} 

Optimizing strategy, timing

  1. Preload Class.forName

Through the above statistics, we know which classes are time-consuming to load, and we can choose to load the corresponding classes (especially many classes of kotlin) in sub-threads at the right time.

Class.forName(className, true, context.classLoader) 

The initialize parameter is set to true, indicating that static code blocks will be initialized, and operations such as assigning static variables

  1. Disable VerifyClass

In the ClassLoader#loadClass process, it must go through defineClass (load class from dex package io), verifyClass (verify instruction), resolveClass (link class, allocate field memory) and init (initialize static variables and code blocks)

If you use Systrace or perfetto tools to check the loading time, among them, VerifyClass takes a lot of time.

Plug-in

Now basically all the apps of major manufacturers use plug-ins, such as WeChat, Douyin and so on. There are several important points in plug-in: loading the class class of the plug-in, the resource resource, and the so of the plug-in.

There are also many pitfalls, such as:

  • Different classloaders will load so of different namespaces, and there is a problem with the interdependence of plug-ins and so of plug-ins;

  • How can the ClassLoader of the plug-in and the ClassLoader of the main package load the classes of the main package and the plug-in package, and also ensure that the same class will not be loaded repeatedly by different classLoaders;

  • The plug-in dex package does not have dex2oat. Generally, we open an additional process to do the dex2oat operation (AOT). After compiling and optimizing, it can be set as the optimizedDirectory of the plug-in ClassLoader, but after 8.0, the optimizedDirectory parameter of the BaseDexClassLoader is useless, which means Plug-in AOT is invalid;

  • Before Android 5.0, AOT was fully compiled during installation, which would become extremely slow; after Android 7.0, JIT and AOT were used, which may cause AOT to start at startup. One of the optimization methods is to suppress or delay AOT. To avoid ANR, optimize startup speed.

Let’s leave the hole on the top first, and wait for it to be sorted out later.

Summarize

If you want to become an architect, don't be limited to coding and business, you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.

If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by a senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically and efficiently. Master the various knowledge points of Android development.
insert image description here
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.

1. The necessary skills for architects to build a foundation

1. In-depth understanding of Java generics
2. Annotations in simple terms
3. Concurrent programming
4. Data transmission and serialization
5. Java virtual machine principles
6. Efficient IO
...

insert image description here

2. Source Code Analysis of Top 100 Android Frameworks

1.Retrofit 2.0 source code
analysis2.Okhttp3 source code
analysis3.ButterKnife source code analysis4.MPAndroidChart
source code analysis5.Glide source
code analysis6.Leakcanary
source code
analysis7.Universal-lmage-Loader source code
analysis8.EventBus 3.0 source code
analysis9.zxing source code Analysis
10. Picasso source code analysis
11. LottieAndroid use detailed explanation and source code analysis
12. Fresco source code analysis - picture loading process

insert image description here

3. Practical analysis of Android performance optimization

  • Tencent Bugly: A Little Understanding of String Matching Algorithms
  • iQiyi: Android APP crash capture solution - xCrash
  • ByteDance: In-depth understanding of one of the Gradle frameworks: Plugin, Extension, buildSrc
  • Baidu APP technology: Android H5 first screen optimization practice
  • Analysis of Alipay client architecture: Android client startup speed optimization "garbage collection"
  • Ctrip: From the Zhixing Android project to see the practice of component architecture
  • Netease News Construction Optimization: How to make your construction speed "like lightning"?

insert image description here

4. Advanced kotlin strengthens actual combat

1. Kotlin introductory tutorial
2. Kotlin actual pit avoidance guide
3. Project actual combat "Kotlin Jetpack actual combat"

  • Start with a Demo that worships the Great God

  • What is the experience of writing Gradle scripts in Kotlin?

  • The Triple Realm of Kotlin Programming

  • Kotlin higher order functions

  • Kotlin Generics

  • Kotlin extensions

  • Kotlin delegation

  • "Unknown" debugging techniques for coroutines

  • Graphical coroutine: suspend

insert image description here

5. Advanced decryption of Android advanced UI open source framework

1. Use of SmartRefreshLayout
2. Source code analysis of Android PullToRefresh control
3. Basic usage of Android-PullToRefresh pull-down refresh library 4. LoadSir -
efficient and easy-to-use loading feedback page management framework Line chart) 7. Hellocharts-android usage guide 8. SmartTable usage guide 9. Open source project android-uitableview introduction 10. ExcelPanel usage guide 11. Android open source project SlidingMenu in-depth analysis 12. MaterialDrawer usage guide








insert image description here

6. NDK module development

1. NDK module development
2. JNI module
3. Native development tools 4.
Linux programming
5. Low-level image processing
6. Audio and video development
7. Machine learning

insert image description here

7. Advanced Flutter technology

1. Overview of Flutter cross-platform development
2. Building the Flutter development environment in Windows
3. Writing your first Flutter APP
4. Building and debugging the Flutter development environment
5. Basic grammar of Dart grammar (1)
6. Part of Dart grammar The use of collections and source code analysis (2)
7. Collection operator functions and source code analysis of Dart syntax (3)
...
insert image description here

8. Wechat Mini Program Development

1. Small program overview and introduction
2. Small program UI development
3. API operation
4. Shopping mall project combat...

insert image description here

Full set of video materials:

1. Interview collection
insert image description here
2. Source code analysis collection

insert image description here
3. Collection of open source frameworks

insert image description here
Welcome everyone to support with one click and three links. If you need the information in the article, just click the CSDN official certification WeChat card at the end of the article to get it for free [guaranteed 100% free]↓↓↓
insert image description here

Guess you like

Origin blog.csdn.net/m0_56255097/article/details/125286576#comments_27467446