This article turns from http://www.devtf.cn/?p=1097
Original link: Speed up your app
Original Author: UDI COHEN
Developed technical front line www.devtf.cn. Without permission, not reproduced!
Translator: Zijianwang90
Proofread by:
Status: Complete
A few weeks ago, I had a speech on Android performance optimization on Droidcon NYC.
I spent a lot of time in this speech because I wanted to show real-life examples of performance issues and what tools I was using to discover them. Because of time, I had to abandon half of the content in the speech. In this article, I'll summarize everything I've discussed in my speech, and give examples
Click this link to enter the presentation video
Now, let's talk about some of the key points I mentioned in my speech, and I hope my elaboration is clear enough. First of all, I followed the following guidelines when I was optimizing my performance:
Principle
Whenever I encounter performance problems, or try to discover performance issues, I follow the following guidelines:
- Stick to performance testing – don't use your eyes to optimize performance. Maybe after you look at the same animation a few times, you will start to believe that he is running more and more smoothly. Data does not lie. Before and after you optimize your code, use the series of tools we'll be introducing to test your app's performance geometry many times.
- Use low-end devices – low-end devices tend to be easier if you want to expose your application's performance problems. Powerful devices tend not to care too much about your application of some of the optimization issues, and not all users are using these flagship devices.
- Tradeoff – the optimization of performance always revolves around the tradeoff between the two words. Your optimizations at one point may cause problems on the other. In many cases, you will spend a lot of time looking for and solving these problems, but the cause of these problems can also be caused by, for example, the quality of bitmaps, or you do not use the right data structure to store your data. So you have to be ready to make some sacrifices.
Systrace
Systrace is a great, but potentially overlooked, tool because developers are often unsure what information systrace can offer them.
Systrace will show an overview of the status of the program running on the phone. This tool reminds us that the phone is actually a computer that can do a lot of work at the same time. In a recent SDK update, this tool has been improved in data analysis capabilities to help us find performance issues.
Let's look at what Systrace looks like:
You can generate the Systrace file from the Android Device Monitor tool or the command line to learn more about the poke here.
In the video, I introduce the functions of different areas in Systrace. Of course the most interesting is the alerts and frames two columns, which show the visual analysis results generated by the data from the phone. Let's choose the top alerts to see:
This warning indicates that there is a View#draw () method that executes for a relatively long time. We can see the description of the problem, links, and even related videos below. Let's look at the frames line below, and we can see that each frame that is drawn is shown here, and the green, yellow, and red three colors are used to distinguish the performance of the drawing. Let's choose a red frame to look at:
At the bottom, we see some caveats related to this frame. Of these three warnings, one is what we mentioned above (View#draw ()). Next we zoom in at this frame and expand the "inflation during ListView recycling" warning below:
We can see the total time spent on the warning part, 32 milliseconds, much higher than the 16 millisecond draw time we need to protect 60fps. There are also more ListView each entry's drawing time, about 6 milliseconds per entry, a total of five. The content in the description description will help us understand the problem and even provide a solution to the problem. Back to our last picture, we can zoom in on the block area of "inflate" and see exactly which view is more time-consuming during the filling process.
Here's another example of a slow rendering:
After selecting a frame, we can press the "M" key to highlight the frame, and at the top we see this part of the time-consuming, we see that this burst of drawing takes more than 19 milliseconds. And when we unfolded the only warning of this frame, we found the error "scheduling delay".
Scheduling delay (dispatch delay) means that a thread has not been assigned to the CPU for a long period of time when it is processing a block of operations, causing the thread to not complete its work for a long time. We select the longest piece in this frame to get more detailed information:
In the red-framed area, we see "Wall duration", which represents the time-consuming period of the start-to-end of this chunk. It is called "Wall duration" because he is like a clock on the wall, timing you from the beginning of the thread.
However, CPU duration shows the time that the actual CPU consumes in processing this chunk.
Obviously, the gap between the two times is still very large. The entire chunk takes 18 milliseconds, while the CPU consumes only 4 milliseconds to operate. This is a bit strange, so we should look at what the CPU is doing in this whole process.
As you can see, all four threads are very busy.
Choosing one of these threads will tell us which program is taking him, and here is a package named Com.udinic.keepbusyapp program. Here, because another program consumes the CPU, our program fails to get enough CPU resources.
However, this is a temporary situation, because the CPU is not seen by other background applications (--), but there are still other application threads or the main thread that consumes the CPU. And TraceView can only provide us with an overview, his depth is limited. So to find out what's really going on in our app to get our CPU busy, we need another tool to--traceview.
Traceview
TraceView is a performance testing tool that shows the elapsed time of all methods. Let's look at what he looks like:
This tool can be opened from Android Device Monitor or by code. Read more about the news here.
Let's take a look at the meaning of each column:
- name– the name of the method and the color they correspond to in the chart above.
- Inclusive CPU time–cpu The total time taken to process this method and all the sub-methods, such as all methods that he invokes.
- Exclusive CPU time–cpu is always time consuming to process this single method.
- Inclusive/exlusive Real time– The total time taken from the start of the method to the end of execution, similar to the "Wall duration" in Systrace
- calls+recursion– the number of times this method was called, and the number of times it was called recursively.
- Cpu/real time per call– The average of the CPU time spent processing this method and the actual time-consuming average. The additional column shows the cumulative time-consuming of all calls to this method
I opened an application that slipped less smoothly. Turn on the record, swipe a bit and stop recording. Expand the GetView () method, such as:
This method is called 12 times, each time the CPU consumes about 3 milliseconds, but the total time spent on each call is as high as 162 milliseconds! Definitely a problem!
And looking at the children of this approach, we can see how each of these methods is distributed over time. The Thread.Join () method is a 98% inclusive real time. This method is called when waiting for the other thread to end. Another method in children is the Tread.start () method, and the whole method takes a long time, I guess because the thread is started in the GetView () method and is waiting for it to end.
But where is this thread?
We do not see what this thread does in the GetView () method, because this logic is not in the GetView () method. So I found the Thread.run () method, which is the method that runs when the thread is created. And following this method all the way down, I found the culprit of the problem.
I found that each invocation of the Bgservice.dowork () method took nearly 14 milliseconds, and there were 40 of these things! And it is possible to call this method multiple times in GetView (), which explains why the GetView () method executes so long. This method keeps the CPU in a busy state for a long time. And looking at exclusive CPU time, we can see that he occupies 80% of the CPU! In addition, depending on the exclusive CPU time sequencing, you can help us to better locate those long-consuming methods that are likely to be the culprit for performance problems.
Focusing on these time-consuming methods, such as GetView (), View#ondraw (), can be a good way to help us find out why the application is running slowly. But sometimes there are other things that can take up valuable CPU resources that, if applied to the drawing of the UI, may be more streamlined. The garbage collector garbage collection mechanism will run periodically, reclaiming useless objects, which generally do not affect the programs we run in the foreground. But if the GC is running too often, he can also affect the execution efficiency of our application. And how do we know if recycling is too frequent ...
Memory Tuning Memories Profiling
Android Studio has given us more powerful tools to analyze performance issues in recent updates. The Memory tab in the bottom Android option shows how much data was allocated to the heap memory, and he grew up like this:
And when a small slide in the chart shows that GC recycling has occurred, he cleans up unnecessary objects and frees up some heap space. On the left side of this chart there are two tools for us to use, Head dump and allocation Tracker.
Heap Dump
To find out exactly what is taking up our heap memory, we can use the heap dump button on the left. He will provide a snapshot of the heap's memory footprint and will open a separate reporting interface in Android Studio.
On the left, we see an icon that shows all the instances in the heap, grouped by class. For each instance, it shows how many instances of the object are allocated to the heap, and the space they occupy (shallow size), and the space that these objects still occupy in memory, which tells us how much of the memory space will be freed if those instances are freed. This tool allows us to visually observe how memory is being used, to help us analyze the relationship between the data structures and objects we use, to identify problems and to use more efficient data structures, to unlock and correlate with objects, and to reduce the ratained memory footprint. And the ultimate goal is to reduce our memory footprint as much as possible.
Looking back at the chart, we found that there are 39 instances of memoryactivity, which is a bit odd for an activity. Select one of these instances on the right, and you will see a list of all references to this instance below.
One of these is a collection of Listenersmanager objects. and observing the other instances of the activity, they are all kept in memory because of this object. This also explains why these objects occupy so much memory:
This phenomenon is called "memory leaks", our activity has been destroyed, but their objects are always referenced and cannot be garbage collected. We can avoid this situation, for example, to ensure that these objects are not being referenced by other objects until they are destroyed. In our example, Listernesmanager does not need to keep a reference to these objects after the activity has been destroyed. So the solution is to remove these references in the OnDestroy () callback method.
Memory leaks and other large objects occupy a large number of controls in the heap, reducing the amount of available memory while also causing frequent garbage collection. While garbage collection is causing the CPU to be busy, and heap memory does not become larger, it will eventually result in more tragic results: outofmemoryexception memory overflow and cause the program to crash.
Another more advanced tool is the Eclipse Memory Analyzer tool (Eclipse MAT):
This tool can do all that Android studio can do, identify possible memory leaks, and provide more advanced search capabilities, such as searching for all bitmap instances larger than 2MB, or searching for all empty rect objects.
Another good tool is leakcanary, a third-party library that can observe objects in your application and make sure that they do not cause leaks. And if there is a leak, there will be a push to remind you where something has happened.
Allocation Tracker
We can find the start and stop buttons of the allocation tracker on the left side of the memory graph. He generates a report of all instances that have been generated within a certain amount of time and is grouped by class classification:
or grouped by method:
It can also tell us which methods or classes have the most instances through an aesthetically pleasing visual interface.
With this information, we can find methods that consume too much memory, cause multiple garbage collections, and are time-sensitive. We can also use this tool to find a lot of short-lived instances of the same class, so we can consider using the idea of object pooling to minimize the creation of too many instances.
Common Memory Tips
Here are some of the rules or tricks I follow when I write code:
- Enumeration has always been a topic of constant discussion on performance issues. Here is a video that discusses enumerations, pointing out the memory space consumed by enumerations, and there is a discussion about this video, and there are, of course, some misleading ones. But is the enumeration really more space-intensive than the usual constants? Yes, sure. But it must be bad? Not necessarily. If you are writing a library and require strong type security, you might be able to use enumerations instead of other methods, such as @intdef. And if you just have a bunch of constants, using enumerations might not be wise. Or that sentence, before you make a decision must weigh and trade-offs.
- Auto Boxing – Automatic Boxing is a boxing process (for example, int to integer) from the original data type to the object type data. Whenever a raw type of data is boxed into an object type data, a new object is created (shocked.) )。 So if there are many times of automatic boxing, it is bound to speed up the frequency of GC execution, and automatic boxing is very easy for us to ignore. The solution, when using these types, is as consistent as possible, if you use the original data type completely in the application, then try to avoid him being automatically encapsulated for no reason. You can use the Memery profiling tool we mentioned above to find these too many object type data, or you can traceview to find similar integer.valueof (), long.valueof () Such a way to determine whether a large number of unnecessary automatic encapsulation occurred.
- HashMap vs arraymap/sparse*array– since the question of automatic boxing is mentioned, then using HASHMAP, we need to use the object type as the key. And if we are using the "int" of the basic data type throughout the application, then we will have automatic boxing when we use HashMap, and perhaps we can consider using Sparseintarray. And if we still need the key as the object type, then we can use Arraymap. Arraymap and HashMap are similar, but at the bottom of the implementation principle is not the same, this will let us more efficient use of memory, but pay a certain performance cost. Both methods will save more memory space than HashMap, but there will be some sacrifices compared to HashMap, the speed of query and deletion. Of course, unless you have at least 1000 data sources, it's not going to have too much impact on speed at run time, which is one of the reasons you use them instead of hashmap.
- Note that context– in front of us also saw that activity is very easy to cause memory leaks. In Android, the most likely cause of memory leaks is activity. And these memory leaks can waste a lot of memory because they hold all of the view in their UI, and these view usually occupy a lot of controls. Many operations in the development process require context, and I usually use activity to pass it on. So be sure to figure out what you've done with this activity. If a reference is cached and the object's lifetime is longer than your activity, then the memory leak will occur before we release the reference.
- Avoid non-static – when we create a non-static inner class and initialize it, an implicit reference to the outer class is created inside it. If the life cycle of the inner class is longer than the outer class, then the outer class is also kept in memory, even though we do not need it at all. For example, within the activity, you create an inner class that inherits from Asynctask, and then starts the async task when the activity is running, and then kills the activty. Then this async task will hold the activity until the end of execution. And the solution is very simple, do not do so, try to use static internal classes.
Monitor GPU (GPU Profiling)
A new tool in Android 1.4 is the ability to view GPU drawing.
Each line means that one frame is drawn, and the different colors in each line represent different stages in the drawing process:
- Draw (blue) represents the View#ondraw () method. In this session, objects in the displaylist are created/refreshed, which are later converted to OpenGL commands that the GPU can understand. The higher the value may be because the view is more complex and requires more time to create their display list, or because too many view is created in a short period of time.
- Prepare (purple) – In the lollipop version, a new thread is added to the UI thread to help draw the UI. This thread is called Renderthread. It is responsible for converting the display list to the OpenGL command and sending it to the GPU. In this process, the UI thread can continue to start processing the subsequent frames. The time consumed by the purple phase is when the UI thread passes all the resources to the renderthread process. If there is a lot of resources to pass through in this process, the display list becomes too heavy to take too long in this phase.
- Process (Red) – Executes the contents of the display list and creates the OpenGL command. If there is too much or too complex a display list to execute, then this phase will take a long time, because there will be a lot of view being redrawn. Repainting often occurs when the interface is refreshed or moved out of the covered area.
- Execute (yellow) – sends OpenGL commands to the GPU. This phase is a blocking call because the CPU only sends a buffer that contains some OpenGL commands to the GPU, and waits for the GPU to return an empty buffer to pass the next frame's OpenGL command again. The total amount of these buffers is certain, if the GPU is too busy, then the CPU will wait for the next empty buffer. So, if we see this phase taking a long time, it could be because the GPU is too busy drawing the UI, and the reason for this might be to draw overly complex view in a short period of time.
In the marshmallow version, more colors were added, such as the measure/layout phase, input handling, and some others:
Before using these features, you need to turn on GPU rendering (GPU rendering mode analysis) in the developer options:
Next we can get all the information we want by following this adb command:
| 12 |
adb Shell dumpsys gfxinfo <package_name> |
We can collect this information ourselves and create charts. This command also prints out some other useful information, such as the number of layers in the view hierarchy, the size of the display lists, and so on. In Marshmallow, we will also get more information:
If we need to test our app automatically, we can create our own server to run the commands on a specific node (such as list scrolling, heavy animation, etc.) and observe the changes in these values. This can help us find out where the performance is falling and where the product is going to go before it goes live. We can also find more and more accurate data through the "framestats" keyword.
63. Accelerated Android App (reprint)