Android app performance analysis methods and tools

Source: Internet
Author: User

Recently read the article "Speed Up your app". This is an article on the Performance analysis and optimization of Android apps. In this article, the author describes his app analysis optimization rules, the tools and methods used. I think we should learn from it. Good English readers can read the original text (link: http://blog.udinic.com/2015/09/15/speed-up-your-app).

1, the author's rules

Each time the author begins to process or look for performance issues, the following rules apply:

    • Frequent detection

Before and after updating the app, you can quickly get the test data by testing the app performance several times with the test tool software. These numbers are not going to lie. It is certainly not possible to observe the app's performance with the eyes alone. If you look at the same animation several times, you can imagine that it's running fast enough to ignore the problem.

    • Using low-end devices

Today's hardware performance is constantly improving, and if you run apps only on the latest devices, you may not be able to fully expose the performance issues that exist in your app. In addition, although the user device turnover rate is already very high, but still not all users are using the latest and strongest features of the device. So you should use the low-end device to run the app, which can help you find the problem more effectively.

    • Weigh

Performance optimization is to synthesize all aspects of the evaluation, trade-offs. Because optimizing a performance may be at the expense of another performance. It takes a lot of time to analyze, find, fix. You must be prepared to sacrifice yourself.

2, the author's analytical methods and use of tools

The author adopts the top-down method, starting from the general situation of mobile phone running, and analyzing in depth: The performance of the method, memory usage, GPU rendering effect, view hierarchy, drawing overlay drawing, image transparency value, explaining the hardware acceleration and the view layer introduced by honeycomb.

2.1 Systrace

Mobile phone is actually a powerful computer, do a lot of things at the same time. Systrace is able to show the overview of mobile phone operation.

The author chooses an alert in systrace as an example to explain the method of discovering the problem:

1) Find the function by alert (for example: Long View#draw ()), and then expand "inflation during ListView recycling"

2) You can view the time-consuming function, and examine in more detail which of these takes a long time.

3) Select a frame to see how long it takes. If one frame is drawn, it takes more than 19ms. Expand "Scheduling Delay"

4) Its value (the difference between Wall duration and CPU duration) indicates that the CPU has not scheduled this thread for a long time.

This is what the CPU has been doing all this time. but Systrace can only view the running profile and not get a deeper analysis. To find the real reason the CPU is running busy, the author uses another tool: Traceview.

2.2 Traceview

TraceView is a profiling tool that shows how long each method will run. Can be launched from Android Device Monitor, or from code.

The author illustrates the TraceView analysis method with the action of "rolling screen" as an example. In the track record of the "scrolling" action, find the GetView () method and find that it was called 12 times, each time the CPU takes about 3MS. But every time the entire call is completed 162ms! That's a problem!

The author continues to view the sub-methods of GetView () to see how long each sub-method takes in the total time. He found that the inclusive Real time of Thread.Join () occupied about 98%. He follows through, looking for the Thread.run () method of the Promoter method (which is the method that is called when creating a new thread), followed by one after another until the "culprit": Bgservice.dowork () method is found.

In addition, the GC (Garbage collector– garbage collector) does not periodically run cleanup of unused objects. The frequent operation of the GC also slows down the app. For this reason, the next step for the author is to analyze the memory.

2.3 Memory Analysis (Profiling)

Android Studio is gradually improving and there are more and more tools available to help us find and analyze performance issues. The author uses it to analyze memory usage.

2.3.1 Heap Dump

Heap dump can see a histogram of the instance sorted by class name in the heap. Each has the total number of allocated objects, the size of the instance, and the size of the object left in memory. The latter tells us how much memory can be freed after these instances are freed. This helps us to identify large data structures and object relationships. This information can help us build more efficient data structures, unlock the connections between objects to reduce memory footprint, and ultimately reduce memory consumption as much as possible.

In the analysis, a "memory leak" can be found. The workaround is to remember to call the Ondestory () method to delete the reference when the activity is about to be destroyed.

Memory leaks and heap space consumption of large objects, resulting in effective memory reduction, frequent GC events, and attempts to free up more heap space. These GC events consume CPU and reduce app performance. If the amount of available memory is insufficient to satisfy the app, and the heap space does not expand, a--outofmemortexception--app crash is thrown.

Eclipse MAT (Eclipse Memory Analyze tool) is also a good memory analyzer.

2.3.2 Allocation Tracker

Allocation Tracker can generate case reports that memory is allocated to all instances during a trace, and reports can be grouped by class or by method. It shows in a good visual way which instance gets the most memory.

Using this information, you can find ways to allocate large memory, and events that can trigger GC frequently.

2.3.3 General Memory Tips

The author gives some tips:

    • Enumeration

has been a hot topic in the discussion of performance. Does an enumeration take up more memory space than a normal constant? Yes. But is this certainly a bad thing? Not necessarily. If you are writing a code base, you need strong type security, which should be used. If you have a set of constants that can be attributed together, it may not be appropriate to use enumerations at this time. How to decide, you need to weigh the consideration.

    • Auto-boxing

is to automatically convert the original data type to its corresponding object representation (for example, int to Integer). Each time the original data type is "boxed" into the object, a new object is generated (I know this is shocking). If there are many such operations, then the GC will run very frequently. Since the original type data is assigned to an object, it is easy to ignore the number of auto-boxing when it is automatically made. The solution is to keep the data types as consistent as possible. If you want to use the original data type throughout your app, try to avoid auto-boxing when you don't have the actual need. Use the Memory Analyzer tool to find many objects that represent the original data type. You can also use TraceView to find integer.valueof (), long.valueof () and so on.

    • HashMap and Arraymap/sparse*array

In auto-boxing related issues, when using HashMap, objects are required as key values. If you use the original int type in your app, you need to convert int to integer when using HashMap. This situation may need to be sparesintarray. You can also use the Arraymap class if the key value still requires an object type. It is very similar to HashMap, but works in a different way internally, using less memory at the expense of speed reduction. Both take up less memory than HashMap, but the time it takes to retrieve is slightly higher than hashmap. If the data items are less than 1000, they run without any difference.

    • Context Awareness

Activity memory is relatively easy to leak. Because they maintain all the view levels of the UI and occupy a lot of space, their leaks are also very "expensive". Many operations require a context object, and you initiate activity. If the reference is cached and the object survives longer than your activity, you create a memory leak if you do not clear its reference.

    • Avoid non-static inner classes (inner class)

Creates a non-static inner class and instantiates it, creating an implicit reference to the external partial. If an internal class instance takes longer than the outer class, the outer class is kept in memory even if it is no longer needed. For example, inside the activity class, you create a non-static class that extends Asynctask, and then you start an asynchronous task that destroys the activity as it runs. The asynchronous task keeps this activity running during its run. The solution is not to do so. If this is required, declare a static inner class.

2.4 GPU Profiling

Android Studio 1.4 Adds a new feature: Analyze GPU rendering capabilities. The author explains in detail the analysis method of this new function.

Under the GPU tab, you can see the amount of time it takes to render each frame in a graphical display on the screen. Each bar in the drawing represents a frame that is rendered. Colors represent the different cycles of a process:

    • Painting (blue)

Represents the View#ondraw () method. That part builds/changes the Displaylist object and then translates it into OpenGL commands that the GPU can understand. High bars can be complex views and require more time to draw their display lists, and many views expire in a short period of time.

    • Preparation (purple)

In Lollipop, join another thread to help the UI thread render faster. This thread is called: Renderthread. Its responsibility is to convert the display list to the OpenGL command and then send it to the GPU. This allows the UI thread to begin processing the next frame during the rendering process. The UI thread then transmits all the resources to Renderthread. This step can take a long time if there are many resources to pass, such as many/heavy display lists.

    • Processing (red)

Perform a display list to generate OpenGL commands. Because a view redraw is required, this step may take a long time if there are many/more complex display lists to perform the conversion. When the view is invalid or moved, the view must be redrawn.

    • Execute (Yellow)

Sends OpenGL commands to the GPU. Because the CPU sends these cached commands to the GPU and expects to reclaim the clean cache, this blocks the call. The number of caches is limited, and the GPU is busy--cpu will find that it has to wait for the cache to be released first. So, if we see a high bar in this step, it could mean that the GPU is very busy drawing the UI, which is too complex for a short time.

Examples of specific operations are shown in the original.

2.5 Hierarchy Viewer

The author loves this tool. He was disappointed that many developers did not use the tool at all.

With the hierarchy Viewer, you can fully observe the screen view hierarchy and the properties of all views. You can also export the subject (theme) data to see all the properties of each style. However, this data can only be viewed when the hierarchy Viewer is running independently. You cannot view it from the Android Monitor.

The author uses this tool when designing layouts and optimizing layouts.

The author believes that there is time for each view to be measured and all its child views. Color represents the comparison of views with other views in the tree, and it is easy to find the weakest link. Since we can preview the view, we can trace the redundant steps that can be removed through the view tree. Among these, the most significant impact on performance is known as Overdraw.

2.6 Overdraw

If the GPU needs to draw a lot of content on the screen, it will need to increase the time to draw each frame so that the execution cycle is elongated and in yellow in the graph. Overlay the drawing on some graphs, such as the yellow button on a red background, which occurs overdraw. In this case, the GPU needs to draw a red background and then draw a yellow button on it, Overdraw is unavoidable. If there are too many overdraw layers, this makes the GPU overloaded and deviates from the 16ms target.

Set the "Debug GPU overdraw" developer option and the severity of all overdraw is expressed in color. A few times the overdraw is good, even some small red area is not bad. But if there's a lot of red on the screen, that's a problem. But they're all covered in red. That's the problem. The author suggests that this problem be solved only by setting the background in one color.

Note: The default theme declares a full-screen window background color. If an activity with an opaque layout overrides the entire screen, you can remove the layer overdraw by removing the window's background color.

The Hierarchy Viewer is able to output all levels into the PSD file and open in Photoshop. Study different layers in Photoshop to show all the overdraw in the layout. Remove redundant overdraw and try to improve performance to blue.

2.7 Alpha

Using transparency effects can also affect performance. Why?

ImageView overlap each other. Sets the alpha value with Setalpha (), which is passed to all the child views, drawing the frame buffer. The results are all overlapping and mixed together. Fortunately, the OS has a solution to this problem. The layout data is copied to the off-screen buffer, and the off-screen buffer is processed with an alpha value and then copied into the frame buffer. The effect is better. However, we paid the price: instead of changing the "frame" buffer to off-screen buffer, we actually added an implied overdraw layer. The OS is not aware of processing, so it is often complicated to operate by default.

However, there are ways to set the alpha value to avoid the complexity of the off-screen buffer increase:

    • TextView

Replace Setalpha () with SetTextColor (). Using the alpha channel of the text color, you can use it to draw text directly.

    • ImageView

Replace Setalpha () with Setimagealpha (). Reason with TextView.

    • Custom View

This complex behavior is irrelevant if the custom view does not support overlay views. You can tell the OS to draw a custom view directly by overriding the Hasoverlappingrendering () method to return false. You can also override the Onsetalpha () aspect to let it return true, choosing to manually process the settings for each alpha value corresponding to the action.

2.8 Hardware Acceleration

After introducing hardware acceleration in honeycomb (hive, Android 3.x), rendering the app on-screen can be a new drawing model (http://developer.android.com/guide/topics/graphics/ hardware-accel.html). The new model introduces the displaylist structure, which records the view render drawing commands. There is another good feature that is often overlooked or incorrectly used by developers-the view layer.

Using the view layer, we can render the view in a non-screen buffer (as seen previously, applying an alpha channel) and manipulate it as we wish. Because this feature makes it possible to draw complex animation views more quickly, it is primarily used for animations. Without these levels, the animation view will not work after you change animation properties such as x-coordinates, scaling, alpha values, and so on. For complex views, this invalid effect is passed to all child views, and the cost of repainting is high. With hardware support, when using the view layer, the GPU creates textures for the view. There are several operations that can be used for textures without breaking it, such as X/y position, rotation, alpha, and so on. All means that during an animation, you can draw a complex animation view on the screen without destroying it at all. This makes the animation smoother.

Here are a few things to keep in mind when using the hardware layer:

    • Cleans up the view. The hardware layer consumes the space and GPU of the limited storage elements. So use it only when you really need it (like an animation) and clean it up afterwards.
    • If you change the view after you use the hardware layer, the hardware layer is invalid and the view is redrawn in a non-screen buffer. This can happen when you change those properties that are not optimized for hardware-only optimizations: rotation, scaling, x/y, transformations, axes, and alpha.
3. Other information

The author prepares a lot of code to simulate a situation to illustrate performance analysis and optimization. This code can be in the GitHub code base (Https://github.com/Udinic/PerformanceDemo) or Google Play (https://play.google.com/store/apps/ Details?id=com.udinic.perfdemo) found. He puts different scenarios into different activity, and they write documents that help to understand what is going on with the activity. You can use tools and run apps to read the Javadoc of your activity.

The author also recommends some ways to learn to communicate:

    1. The authors strongly recommend watching a group of Android performance patterns videos on YouTube (https://www.youtube.com/playlist?list= PLOU2XLYXMSIKEOXH5TWZEV89AOFHZNCIU), many of these short videos come from Google, explaining different performance topics.
    2. Join Android Performance Patterns Google + community (https://plus.google.com/communities/116342551728637785407), You can discuss performance, share ideas, articles, and ask questions with others, including Google people.
    3. More Interesting links:
    • Learn how the Android graphics Architecture (http://source.android.com/devices/graphics/architecture.html) works. Here are everything you need to know about how Android renders the UI, explaining different system elements, such as Surfaceflinger, and how they interact with each other. This document is very long, but it is worth reading.
    • About Google IO 2012 talk (Https://www.youtube.com/watch?v=Q8m9sHdyXnE), shows how the drawing model works, and how/why there is a jank in the UI rendering.
    • Android Performance Workshop (Https://www.parleys.com/tutorial/part-2-android-performance-workshop), starting with Devoxx 2013, showing Android Some optimizations for the drawing model in 4.4 demonstrate different performance optimization tools (Systrace,overdraw, etc.).
    • For a lengthy article on preventative optimization (HTTPS://MEDIUM.COM/GOOGLE-DEVELOPERS/THE-TRUTH-ABOUT-PREVENTATIVE-OPTIMIZATIONS-CCEBADFD3EB5), Explains what this is different from early (premature) optimization. Because many developers think the impact is not obvious, they do not optimize their part of the code. Keep in mind that a little bit is a big problem. If you have the opportunity to optimize a small portion of your code, be afraid it may be minimal and don't give up optimization.
    • Android Memory Management (HTTPS://WWW.YOUTUBE.COM/WATCH?V=_CRUQY55HOK) This is the old video of Google IO 2011. It still has a lot of meaning. It shows how Android manages the memory of the app and how to use tools such as Eclipse MAT to identify problems.
    • Google engineer Romain Guy's case study (http://www.curious-creature.com/docs/android-performance-case-study-1.html), how to optimize the Twitter client. In this case study, Romain shows how he found performance issues in the app and how he suggested modifying them. In one post, the other issues that arose after the redesign of the same app were shown.

The author hopes that everyone has obtained enough information and a stronger confidence. To optimize your app! from today onwards

The author's speech video on performance optimization is here: http://www.youtube.com/embed/v3DlGOQAIbw?color=white&theme=light

Android app performance analysis methods and tools

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.