Android performance optimization: take you hand in hand to fully realize memory optimization

 

foreword

  • In Android development, performance optimization strategies are very important
  • This article mainly explains memory optimization in performance optimization, I hope you will like it

content


 

1. Definitions

Optimize the memory usage and space usage of the application

2. Function

Avoid problems such as memory leak (ML), memory overflow (OOM), and excessive memory usage due to improper use of memory & lack of management, which will eventually lead to application crashes (Crash)

3. Reserve knowledge: Android memory management mechanism

3.1 Introduction


 

Next, the memory allocation & recycling of the recycling process, objects, and variables will be explained in detail.

3.2 Memory Policy for Processes

a. Memory allocation strategy

The memory allocation of all processes is centrally managed by ActivityManagerService

b. Memory reclamation strategy

  • Step 1: Application Framework determines the type of process to be recycled Processes
    in Android are managed; when the process space is tight, processes will be automatically recycled in the order of process priority low->>high

Android divides processes into 5 priority levels, as follows:


 
  • Step 2: The Linux kernel actually recycles the specific process
    1. ActivityManagerService scores all processes (the score is stored in the variable adj)
    2. Update score to Linux kernel
    3. Real memory reclamation done by the Linux kernel

Only the process is summarized here. The process is complicated. Interested readers can study the system source code ActivityManagerService.java

3.3 Memory strategy for objects and variables

  • Android's memory strategy for objects and variables is the same as Java's
  • Memory management = object/variable memory allocation + memory release

Next, the memory allocation & memory release strategy will be explained in detail

a. Memory allocation strategy

  • Object/variable memory allocation is automatically handled by the program
  • There are 3 types: static allocation, stack allocation, & heap allocation, for static variables, local variables & object instances respectively
  • The details are as follows

 

Note: Explain memory allocation with an example

public class Sample {    
    // 该类的实例对象的成员变量s1、mSample1 & 指向对象存放在堆内存中 int s1 = 0; Sample mSample1 = new Sample(); // 方法中的局部变量s2、mSample2存放在 栈内存 // 变量mSample2所指向的对象实例存放在 堆内存 public void method() { int s2 = 0; Sample mSample2 = new Sample(); } } // 变量mSample3的引用存放在栈内存中 // 变量mSample3所指向的对象实例存放在堆内存 // 该实例的成员变量s1、mSample1也存放在堆内存中 Sample mSample3 = new Sample(); 

b. Memory release strategy

  • The memory release of objects/variables is handled by the Java garbage collector (GC)/frame stack
  • The memory release strategy of object allocation (ie heap allocation) is mainly explained here = Java garbage collector (GC)

Since static allocation does not need to be released, and stack allocation is only automatically pushed out and into the stack through the frame stack, it is relatively simple, so it will not be described in detail.

  • Java garbage collector (GC) memory release = garbage collection algorithm, mainly including:

 
  • The details are as follows

 

4. Common memory problems & optimization solutions

  • Common memory problems are as follows

    1. memory leak
    2. memory thrashing
    3. Image Bitmap related
    4. Code Quality & Quantity
    5. Incorrect daily use
  • Below, I will analyze the memory problem of each item in detail & give the optimization plan

4.1 Memory leak

  • The introduction
    is ML (Memory Leak), which refers to the phenomenon that after a program applies for memory, when the memory is no longer needed but cannot be released & returned to the program

  • The impact on the application is
    easy to cause the application to overflow memory, that is, OOM

Introduction to memory overflow:


 
  • The essential reason for the memory leak

 

4.2 Image resource Bitmap related

  • The reason
    for optimization is why to optimize the image Bitmap resource, as shown in the following figure:

 
  • The optimization direction
    mainly optimizes the use of image Bitmap resources & memory management from the following aspects

 
  • Specific optimization scheme
    Below, I will explain in detail the specific optimization scheme for each optimization direction

For a more specific introduction, please see the article: Android performance optimization: those little things about Bitmap optimization


 

4.3 Memory thrashing

  • Introduction

 
  • The optimization scheme
    should try to avoid creating a large number of temporary small objects frequently

4.4 Code Quality & Quantity

  • Optimization reasons
    The quality of the code itself (such as data structures, data types, etc.) & quantity (the size of the code amount) may cause a lot of memory problems, such as large memory usage, low memory utilization, etc.

  • The optimization scheme
    is mainly optimized from the total amount of code, data structure, data type, & data object reference, as follows

4.5 Common Use

  • Optimization Reasons
    Some common uses can also cause a lot of memory problems, which I will describe in detail below.

  • Optimization


 

Note:

  1. There is also an ultimate solution for memory optimization: increase the heap memory size of the virtual machine Dalvik
  2. That is, add an android:largeHeap attribute (value = true) in the application tag of AndroidManifest.xml to notify the virtual machine application that a larger heap memory is required
  3. But this practice is not recommended & discouraged

4.6 Additional Tips

Here, there are some memory optimization tips I want to tell you

  • Tip 1: Get the currently available memory size
    Call the ActivityManager.getMemoryClass() method to get the memory size available for the current application (unit = megabytes)

  • Tip 2: Get the current memory usage
    At any stage of the application life cycle, call onTrimMemory() to get the current memory usage of the application (identified by memory level), and release memory according to the memory tension level parameter returned by this method

An API provided after Android 4.0


 
  • Tip 3: When the view becomes hidden, release the memory
    When the user jumps to a different application & the view is no longer displayed, the resources occupied by the application view should be released
  1. Note: Releasing the occupied resources at this time can significantly improve the cache processing capacity of the system
  2. Specific operation: After implementing onTrimMemory() of the current Activity class, the user will be notified when the user leaves the view; if the returned parameter = TRIM_MEMORY_UI_HIDDEN, it means that the view becomes hidden, and the resources occupied by the view can be released.

5. Analysis tools to assist memory optimization

  • Even if you fully understand the reasons for memory, it is inevitable that there will be memory problems that are difficult to find by humans.
  • The following will briefly introduce several mainstream auxiliary analysis memory optimization tools, namely:
    1. MAT(Memory Analysis Tools)
    2. Heap Viewer
    3. Allocation Tracker
    4. Android Studio 的 Memory Monitor
    5. LeakCanary

5.1 MAT(Memory Analysis Tools)

  • Definition: An Eclipse Java Heap memory analysis tool - >> download address
  • Function: View the current memory usage

By analyzing the memory snapshot of the Java process HPROF analysis, quickly calculate the size occupied by the objects in memory, see which objects cannot be collected by the garbage collector & can visually see the objects that may cause this result through the view

5.2 Heap Viewer

  • Definition: A Java Heap memory analysis tool
  • Role: View the current memory snapshot

You can view what types of data are in the total heap memory & the proportion of various types of data

5.3 Allocation Tracker

5.4 Memory Monitor

  • Introduction: A graphical memory detection tool that comes with Android Studio

  • Role: Track system/application memory usage. The core functions are as follows


 

5.5 LeakCanary

So far, all the knowledge about memory optimization has been explained

6. Summary

  • This article mainly explains the relevant knowledge of memory optimization, which is summarized as follows:

 

Link: https://www.jianshu.com/p/9745a9375191  Please indicate the original link for reprint

Next, I will continue to explain the knowledge of performance optimization in Android in depth. If you are interested, you can continue to pay attention.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325342067&siteId=291194637