Profiler analyzes memory jitter, Memory Analyzer (mat) analyzes memory leaks (do not know how to cut me)

Foreword: I recently reviewed the Android performance optimization systematically. Blogging is both learning and recording, and I hope to help other students while recording. Recently I think I came up with a series that I don’t understand. "Don't know how to beat me", "Don't know how to cut me", "Don't know how to beat me"

1. Profiler analyzes memory jitter

In our development project, if you are not careful, memory jitter will often occur. And some memory jitter may also cause our program to freeze or even leak. Next, use the Profiler that comes with Android Studio to analyze memory jitter.


1.1. Simulate memory jitter and open Profiler

First create a section of memory jitter code in MainActivity:

private Handler mHandler = new Handler() {
    
    
        @Override
        public void handleMessage(@NonNull Message msg) {
    
    
            super.handleMessage(msg);
            //创造内存抖动
            for (int i = 0; i < 100; i++) {
    
    
                String arg[] = new String[100000];
            }
            mHandler.sendEmptyMessageDelayed(0, 30);
        }
    };

Then click the button in the red box below to run the program


The following figure appears after running,


Move the mouse to MEMORY and double click to enter the memory analysis


If your project is already running, you can also open it through View --> Tool Windows --> Profiler


1.2, analyze memory jitter

Click the button to trigger the code of memory jitter, take a look at our memory, you can see that it is jagged

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-It94iFlb-1589018239602)(https://user-gold-cdn.xitu.io/2020/5/9 /171f780686912499?w=1613&h=558&f=png&s=124757)]

Click the record in the red box above, and then click stop to analyze a section of our jagged, as shown in the figure:

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-FaU9X4Ny-1589018239603)(https://user-gold-cdn.xitu.io/2020/5/9 /171f7861f6544a55?w=1620&h=536&f=png&s=141052)]

Allocations: Indicates the number of current allocations
Shallow Size: Indicates the current memory usage

You can see that our String[] occupies the most. After left-clicking on String[], all String[] will appear on the right, and then left-clicking on any one, Allocation Call Stack: memory allocation stack information will appear:

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-qG6fCUWG-1589018239606)(https://user-gold-cdn.xitu.io/2020/5/9 /171f78b3a26c5377?w=1619&h=688&f=png&s=194039)]

It can be clearly seen that in our code, it is because of handleMessage:21, MainActivity$1 (com.leo.memoryanalyzertest), which causes memory jitter. Right-click this item and click Jump to Source. You can jump to our problem code. This is how our Profiler analyzes memory jitter.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-iUvBSwKD-1589018239607)(https://user-gold-cdn.xitu.io/2020/5/9 /171f78deef594435?w=597&h=79&f=png&s=9879)]

1.3. If you use the traceView method of the previous article, that is, the CPU Profiler method

First of all, we speculate that traceView is a powerful tool for analyzing lag, and of course it can be measured here. But be aware that it is biased towards time-consuming situations. As mentioned in the previous article, I won’t explain it here. Also click CPU, then record, stop to record a section. Come to our Top Down as shown:

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-6StOqYUE-1589018239608)(https://user-gold-cdn.xitu.io/2020/5/9 /171f7d30377e0bf7?w=1616&h=432&f=png&s=76401)]

You can see that the time-consuming time is in the MessageQueue, which is also related to our memory jitter code, which is sent every 30ms. In handleMessage(), it also indicates that the code is in com.leo.memoryanalyzertest.MainActivity. It can be found that this way of analysis is not obvious.

Note: We all know about memory jitter. If we want to look for it, we should also look for loops or frequent calls. So looking at it this way, we can roughly confirm the location of the problem code by using the CPU Profiler.


2. Analyze memory leaks by Memory Analyzer

Similarly, we first create a memory leak code, first define an interface

public interface CallBack {
    
    
    void leoFun();
}

Then create a static list, add CallBack instance

public class CallBackManager {
    
    
    public static ArrayList<CallBack> sCallBacks = new ArrayList<>();

    public static void addCallBack(CallBack callBack) {
    
    
        sCallBacks.add(callBack);
    }

    public static void removeCallBack(Callback callback) {
    
    
        sCallBacks.remove(callback);
    }
}

Then create a BitmapActivity to implement the CallBack interface, set a large image main_bg, and at the same time, if the instance is in the static sCallBacks, so that every time BitmapActivity is opened and then exited, the BitmapActivity will not be recycled.

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bitmap);

        ImageView imageView = findViewById(R.id.image);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.main_bg);
        imageView.setImageBitmap(bitmap);
        CallBackManager.addCallBack(this);
    }

In this way, we keep opening this page and then close it to see the memory situation, as shown in the figure, we can see that the memory rises directly:

Red box 1: The function is to actively initiate a gc. The purpose is to reclaim some recyclables, phantom references, etc. Avoid memory analysis interference
Red box 2: Heap dump, convert memory allocation into hprof file. (Note that this is the hprof file of the studio, if you need to use the Memory Analyzer to analyze it, it must be converted into a standard hprof file)

Right-click Export to store the file in the folder.
[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-UXAYTrwP-1589018239611)(https://user-gold-cdn.xitu.io/2020/5/9 /171f804db306f156?w=406&h=202&f=png&s=11520)]

Convert into hprof file recognized by mat, as long as the cmd command line comes to the hprof-conv.exe file that comes with our studio, enter the command to convert

hprof-conv source file path output file path, thus generating our my.hprof


2.1. How to use our Memory Analyzer

After generating the hprof file, then use Memory Analyzer.
The download address of the official website: https://www.eclipse.org/mat/downloads.php , because donations are not recommended. I found a more reliable version, download from csdn

After downloading, start our MemoryAnalyzer.exe. File --> Open Heap Dump to open our my.hprof file as shown:

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-VultZtAS-1589018239616)(https://user-gold-cdn.xitu.io/2020/5/9 /171f88c66a73a658?w=1672&h=866&f=png&s=74494)]

First briefly introduce the information of Memory Analyzer.

2.1.1. Red box 1: OverView general information

  • Size Memory size
  • Classes: class object
  • Objects: the number of Objects, that is, the number of instances
  • Unreachable Objects Histogram: Objects that can be recycled and thrown in memory

2.1.2. Red box 2: Histogram histogram

  • Objects: how many instances of this class
  • Shallow Heap: Memory occupied by a single instance
  • Retained Heap: How much memory a single instance and its references occupy

We can use the histogram to search for our first memory leak case in Regex. Search BitmapActivity as shown in the figure, you can see that our BitmapActivity has 3 instances:

We can right-click com.leo.me,oryanalyzertest.BitmapActivity --> List objects --> with incoming reference (who quoted me), as shown in the figure, we can see that there are 3 places where BitmapActivity is referenced:

At this point, we right-click an instance and click Path To GC Roots --> with all refrence, as shown in the figure, find the file with the little sun under the file, which may trigger the memory overflow. This is to say that our sCallBacks is referenced, and it is also confirmed that the static collection sCallBacks in the CallBackManager in our memory leak code has added it.


2.1.3. Red box 3: dominator tree shows the memory and proportion of each instance

You can see that the big head here is bitmap.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-Z2MXW4F3-1589018239623)(https://user-gold-cdn.xitu.io/2020/5/9 /171f869560338e9c?w=1448&h=209&f=png&s=32203)]

Similarly, we can right-click an instance Path To GC Roots --> with all refrence as shown in the figure, and we can also see that our sCallBacks is referenced:

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-YXLRYn0a-1589018239624)(https://user-gold-cdn.xitu.io/2020/5/9 /171f86d44c60df13?w=716&h=387&f=png&s=43407)]


2.1.4. Red box 4: OQL, similar to our memory situation in database search

After writing the command, click the red exclamation mark to run, as shown in the figure

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-HplpQ0dW-1589018239625)(https://user-gold-cdn.xitu.io/2020/5/9 /171f870f6aa8ce57?w=670&h=350&f=png&s=25925)]


2.1.5. Red box 5: thread overview, showing thread status


2.1.6. Red box 6: Top Consumers (emphasis), which directly shows the large memory in our memory

Show that our memory occupies a relatively large amount of memory, you can see that this place is occupied by 3 big bitmaps. Intuitive for analysis


2.1.7. Red box 7: Leak Suspects (emphasis), directly give the analysis, analyze the possible memory leaks in our code

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-0JPPBQZT-1589018239628)(https://user-gold-cdn.xitu.io/2020/5/9 /171f879c46453d10?w=832&h=680&f=png&s=56188)]

Here I started BitmapActivity 3 times, and it also gave me 3 analyses. Click details. Looking at the details, I also directly fixed the problem in sCallBacks:

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-64JHGAkL-1589018239629)(https://user-gold-cdn.xitu.io/2020/5/9 /171f87de82e08ede?w=873&h=445&f=png&s=55325)]


My official account

Will post some practical and vernacular articles. I have also been looking for the most advantageous interview techniques. Classmates who have ideas can be together

Guess you like

Origin blog.csdn.net/leol_2/article/details/106024932