Reprint please indicate the source (do not reprint delete bottom Weibo, etc information):
http://blog.csdn.net/Y1258429182/article/details/51176424
This article is from: Yang Zheji's Blog
The last article summarizes the problem of layout optimization, if the layout optimization is not very familiar, you can look at the Android Studido application performance Optimization summary – layout optimization, this week has been planning to summarize the memory optimization problem, because now for the application optimization of the article many, But still want to improve a bit to share this article, I will from the project encountered a problem, through the process of solving problems to share knowledge, I hope you have a harvest.
"A small leak would sink a great ship."-Benjamin Franklin
The small building does not mend, the big ship also can turn over. --Benjamin Franklin
Problems that arise (what)
- scene: y June a certain day a month encountered a strange problem: a page jump to the B page, and then jump to the other page no problem, but in a jump B, and then B jump to a page, the beginning of the stutter, the program does not crash!! OMG, this is what problem, y June at that time really a little crazy, this is swollen is a situation, but Y June is also on the hell under the fire, in the bug heap out of the person (suddenly think of that sentence, I want to become a man of the king of Thieves ...) ), pull away, or return to the question.
Analysis Issues (WHY)
Because of the fact that there is a lot of memory, we start to analyze the memory usage of our application, but the question is, what tools are used to see the memory usage of the app?
Because previous ecliplse memory viewing was slightly cumbersome, and Goole launched the new development tool for Android Studio, there are a lot of us handy for our Android Development Program Ape Debugging and analysis issues, here I'll introduce Android Memory analysis tool in studio, if unfamiliar can be indicated by the arrow, click on the application of the corresponding package name, you can view the application memory situation, analysis of the following
- Y June processing memory or have a little experience, not anxious to light up their own long-cherished memory analysis of the Three Musketeers:
- Leakcanary
- Memory Analyzer Tool (MAT)
- TraceView
- So we're starting to analyze where the problem is. Go!
How to use Leakcanary
Leakcanary's GitHub Address
Tool Description : leakcanary is square open source of a memory leak automatic detection artifact, it is an Android and Java memory Leak detection library, can greatly reduce the development of oom problems encountered, for Android developers, is undoubtedly a boon.
GitHub has been introduced in detail, I am here to briefly introduce how to use!
Add the Build.gradle file in the project:
{ debugCompile ‘com.squareup.leakcanary:leakcanary-android:1.4-beta2‘ releaseCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2‘ testCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2‘ }
Initialize inside application
publicclass ExampleApplication extends Application { @OverridepublicvoidonCreate() { super.onCreate(); LeakCanary.install(this); }}
When normal access is present, the test application will receive a notification when there is insufficient memory, as follows
But y June's This bug appeared this analysis, did not receive the notice, as follows
- Leakcanary is the main advantage is that the automatic early detection of memory leaks, configuration simple, crawling intimate, the disadvantage is that there are still some bugs, but the normal use of 90% is OK, and then I became the 10%, the specific problem I do not know, But it does not prevent this is a good check tool.
How to use the Memory Analyzer Tool (MAT)
Mat Standalone Memory Detection Tool download
Tool Description : MAT (Memory Analyzer tool) tools in the analysis of large memory dump files, you can very intuitively see the amount of memory used by each object in the heap space, the number of class instances, object reference relations, the use of OQL object query, And can easily find the object GC roots information, of course, the most attractive is also able to quickly generate a memory leak report for developers, easy to locate problems and analyze problems.
Test Demo: I wrote a demo to simulate the situation I encountered at that time! Let the timer always send the message to the handler refresh time, the code is as follows
Private void GetCurrentTime() {//To test more clearly NewThread () {@Override Public void Run() {Super. Run (); while(flag) {//Systemclock.sleep (+); LongEndTime = System.currenttimemillis ();LongTime = Endtime-mstarttime; String result =NewSimpleDateFormat ("Mm:ss"). Format (NewDate (time)); Message message = Handler.obtainmessage (); Message.what = Messageconstants.updatetimeflag; Mfinallytime = result;//In order to jump carry dataMessage.obj = result; Handler.sendmessage (message); }}}.start (); }
- Step one: I only talk about how to crawl memory usage under Android Studio, click the arrow in the top left corner, will crawl your corresponding location of memory usage, 4
- Step two: Wait a moment, the resulting file will appear in captures, then select the file, right-click to convert to the standard hprof file, you can open in the mat.
Again I explained that there are two types of mat, one for the Eclispse plug-in version and one for the standalone version, because we use the standalone version of the mat for Android studio.
- Step three: After opening the crawled file in the mat, the following
There are a lot of features in the mat, so we just have to learn a few of the most common ones. The most central pie chart shows the ratio of the largest number of objects to the amount of memory that is provided in this graph, and we can ignore it.
The red box in the picture has the modules that we use frequently, and their responsibilities are:
- Histogram can list the name, number, and size of each object in memory.
- Dominator Tree sorts all in-memory objects by size, and we can parse the reference structure between objects.
analysis of the Dominator Tree in Mat
Now click on Dominator Tree, as follows:
This picture contains a lot of information, I come with you to analyze. First the retained heap represents the total memory of this object and other references it holds (both direct and indirect), so the first two rows of the retained heap are the largest, and when we analyze memory leaks, the largest memory object is also the most suspect.
In addition, you should be able to notice that there is a file-type icon on the leftmost side of each line, some of which have a red dot in the lower left corner, or none. Objects with red dots indicate that they can be accessed by GC roots, and the objects that can be accessed by GC Root cannot be recycled, as explained above. So does this mean that all red objects are leaking objects? Of course not, because some object systems need to be used all the time and should not be recycled. We can notice that all of the objects with the red dots have a system Class on the far right, indicating that this is a managed object, not an object created by ourselves and causing a memory leak.
Can't you see the reason for the memory leak? It is true that memory leaks are not so easily identified, and we need to analyze them further. In addition to the line with the system class, the largest is the first row of the MessageQueue object, although the MessageQueue object can not now be accessed by the GC roots, but does not mean that bitmap hold other references will not be the GC Roots access to. Now we can go to the second row right-click Path to GC Roots-exclude weak references, why choose Exclude weak references? Because a weak reference does not prevent the object from being reclaimed by the garbage collector, we exclude it directly here, as shown in the following example:
Finally we found the culprit, open a lot of threads, while the dead loop does not stop, I jump when I did not turn off the loop, so there are so many thread.
analysis of the histogram in Mat
First we learn the use of histogram, back to the overview interface, click Histogram, as shown in
Here is the current application of all the names of all the objects, the number and size are listed, it is important to note that What does the shallow heap mean when all the objects here are only shallow heap and no retained heap? Is the size of the current object's own memory, does not include the reference relationship, for example, the shallow heap of the string object is the highest, indicating that our application uses a lot of string type of data, we constantly send handler constantly authoring string objects. You can see who is using these strings, the analysis, and the discovery of the eggs by right-click List objects, with incoming references.
So how do you analyze the causes of memory leaks through histogram? Of course, you can also use and Dominator tree in a similar way, that is, the analysis of large memory objects, such as byte[] object memory consumption is very high, we through the analysis of byte[], and finally can find the memory leaks, But here I'm going to use another way that's better for histogram. As you can see, the number of objects can be displayed in histogram, so for example, we now suspect that there may be a memory leak in mainactivity, you can search for "mainactivity" in the Regular expression box in the first row, as follows:
As you can see, all the objects containing the word "mainactivity" are listed here, with the first line being an instance of mainactivity. However, it has not been noted that there are 30 instances of mainactivity in memory, which is not normal, in case an activity should have only one instance. In fact, these objects are because we have just kept on the screen switching between the production, because the screen switch once, the activity will go through a re-creation process, but because of the existence of Leakclass, the previous activity can not be recovered by the system, Then there is a case where there are multiple instances of this activity.
Next to the mainactivity right-click List objects, with incoming references view the specific mainactivity instance as shown in
Found the same as the above effect, but the comparison of the above method is more convenient, if you can not determine which acitivity out of the problem, you can not deal with, so it is recommended to use Dominator tree to analyze the problem.
Summary: This is probably the most common use of the mat tools, of course, it is also necessary to remind you that the tool is dead, the person is alive, mat there is no way to ensure that the cause of the memory leak can be found out, or need us to the code of the program has enough knowledge, know which objects are alive, And the reasons for their survival, and then combined with the data of mat to carry out specific analysis, it is possible to put some deep hidden problems to find out the cause.
How to use TraceView
Learn from a lot of traceview analysis, found to be copied to copy, and ultimately is a solution, not for various problems to solve the problem, against the problem I encountered this time, I slowly pondering the use of such tools, and found that directly can analyze the specific method to occupy the CPU time, Personally think of memory optimization from the CPU perspective, you can consider using this tool to analyze.
How to use open DDMS, and then
First press Start Method Profiling (Arrow Point, start with red dots), click on the red dot into a gray small box, and then after a while can press stop Method Profiling, and then appear this with the answer card, we only see the next part of the analysis
Obviously, after analyzing the Intel CPU Time property, clicking on it in order from large to small, we clearly found that the run () method actually accounted for 93% of the CPU running memory, and directly to which class inside the method. Some of the remaining properties are estimated to be useful, and I won't introduce them here! If you want to learn more, click on the reference link at the end of the article.
Problem Solving (how)
The analysis results analyzed by these three methods:
1. Leakcanary Feedback Information No, unable to analyze
2. The Memory Analyzer Tool (MAT) feedback information is created in mainacitity a lot of thread, can directly analyze the problem of the dead loop
3. TraceView through the use of the CPU is very intuitive to show that the mainacitivity in the Run () method occupies 95% of the use of clean analysis of the problem
Last solution : add 1s of sleep time, a jump to the B page, turn off the loop!!
Summarize
The article also writes to the last:
If you experience problems with the lag, the recommended steps for analysis are:
1. Memory Usage First
2. Using Leakcanary to see if you can directly analyze the error of the class
3. If the steps of the Leakcanary analysis are not clear enough, the export file is analyzed with Mat
4. If you do not check out any errors in the mat, you can try TraceView to analyze the memory usage, as it can be specific to which method.
Reference article:
1. Android Best performance Practice (ii)--Analysis of memory usage
2. Correct use of the Android profiling tool--traceview
3. The neglected memory Leaks of Android performance optimization
Problem modification:
Tips: Thanks to Pleasecallmecoder's errata! Modified the description of TraceView!
Welcome to follow my Weibo:
http://weibo.com/u/5345060833
Follow the public number: Yangzheshare
(Welcome to pay attention to the latest and most useful technical dry sharing)
Summary of application performance optimizations under Android Studio-memory optimization