Android APP performance analysis methods and tools, androidapp

Source: Internet
Author: User

Android APP performance analysis methods and tools, androidapp

I recently read Speed up your app. This is an article about Performance Analysis and Optimization of Android apps. In this article, the author introduces the APP analysis and optimization rules, and the tools and methods used. I think it is worth your reference. Good English reader readable original (link: http://blog.udinic.com/2015/09/15/speed-up-your-app ).

1. Author's rules

The author follows the following rules every time he starts to deal with or look for performance problems:

  • Frequent Detection

Before and after the APP is updated, use the test tool software to check the APP performance multiple times to quickly obtain the test data. These numbers do not lie. However, simply observing APP performance with your eyes is definitely not good. If you observe the same animation effect several times, you can imagine it is running fast enough to ignore the problem.

  • Use low-end devices

Nowadays, the hardware performance is constantly improved. If you only run the APP on the latest device, the performance problems in the APP may not be fully exposed. In addition, despite the high switch rate, not all users use the latest and most powerful devices. Therefore, you should use low-end devices to run apps, which can help you discover problems more effectively.

  • Trade-offs

Performance optimization is to judge and weigh all factors. Because optimizing one performance may be at the cost of another performance. Analysis, search, and repair take a lot of time. You have to prepare for self-sacrifice.

2. Author's analysis methods and tools

The author uses the top-down method to analyze the running status of mobile phones step by step: the method performance, memory usage, GPU rendering effect, view level, Graphic Overlay rendering, and image transparency value explain the hardware acceleration and view layer introduced by Honeycomb.

2.1 Systrace

A mobile phone is actually a powerful computer that does many things at the same time. Systrace displays the running status of mobile phones.

In Systrace, the author selects an Alert as an example to explain how to find the problem:

1) Find the function (such as long View # draw () by Alert, and then expand "Inflation during ListView reconfiguring"

2) You can view the time consumed by the function. For more information, see which function takes a long time.

3) Select a frame to view how long it takes. If a frame is drawn for more than 19 ms. Expand Scheduling delay"

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

In this case, you need to check what the CPU has done throughout this period? However, Systrace can only view the running status, but cannot get a deeper analysis. To find out why the CPU is busy, the author uses another tool: Traceview.

2.2 Traceview

Traceview is a performance analysis tool that displays the running time of each method. It can be started from Android Device Monitor or from code.

The Traceview analysis method is illustrated by taking the "scrolling" action as an example. In the tracking record of the "scrolling" action, find the getView () method and find that it has been called 12 times. Each time the CPU usage is about 3 ms. However, it takes 162 ms to complete the entire call! This is a problem!

The author continues to view the submethods of getView () and shows the ratio of the time used by each submethod to the total time. He found that the random Real Time of Thread. join () takes about 98%. He finds the Thread of the promoter method. run () method (it is the method called when a new thread is created), followed one by one until the "culprit" is found: BgService. doWork () method.

In addition, GC (Garbage Collector-Garbage Collector) occasionally runs to clean unused objects. Frequent GC operation also slows down APP operation. Therefore, the next step is to analyze the memory.

2.3 Memory analysis (Memory Profiling)

Android Studio is gradually improving. More and more tools are available to help us locate and analyze performance problems. The author uses it to analyze memory usage.

2.3.1 Heap dump

Heap Dump shows the histogram of instances sorted by class name in Heap. Each has the total number of allocated objects, the instance size and the size of objects left in memory. The latter tells us how much memory can be released after these instances are released. This helps us identify big data structures and object relationships. This information can help us build a more effective data structure, unlink objects to reduce memory resident, and ultimately reduce memory usage as much as possible.

During the analysis, we can find "Memory leakage ". The solution is to call the onDestory () method to delete the reference when the activity is about to be destroyed.

Memory leakage and heap space occupation of large objects can reduce the effective memory, frequently cause GC events, and attempt to release more heap space. These GC events occupy CPU and reduce APP performance. If the number of valid memory is insufficient and the APP is sufficient, and the heap space cannot be expanded, the -- OutOfMemortException -- APP crash will occur.

Eclipse Memory Analyze Tool is also a good Memory analysis Tool.

2.3.2 Allocation Tracker

Allocation Tracker can generate a situation report that memory is allocated to all instances during the tracking period. Reports can be grouped by class or by method. It visually shows which instance gets the most memory.

With this information, you can find out how to allocate large memory and events that may frequently trigger GC.

2.3.3 General memory tips

The author provides some tips:

  • Enumeration

It has always been a hot topic about performance. Does enumeration occupy more memory space than normal constants? Yes. But is this definitely a bad thing? Not necessarily. For example, if you want to write a code library that requires strong type security, you should use it. If there is a group of constants that can be attributed together, it may not be appropriate to use enumeration. You need to consider how to decide.

  • Auto-boxing

Is to automatically convert the original data type to its corresponding object representation (for example, int to Integer ). Every time the original data type is "boxed" to an object, a new object is generated (I know this is shocking ). If there are many such operations, GC runs frequently. Since the original type of data is automatically auto-boxing when assigned to an object, it is easy to ignore its quantity. The solution is to try to make the data types consistent. If you want to use the original data type in the entire APP, try to avoid Auto-boxing when there is no actual need. Using the memory analysis tool, you can find that many objects 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 problems, when HashMap is used, the object must be used as the key value. If the original int type is used in the APP, the int type needs to be converted to an Integer when HashMap is used. In this case, SparesIntArray may be used. If the key value still needs the object type, you can also use the ArrayMap class. It is very similar to HashMap. It only works in different internal ways and uses less memory at the cost of reducing the speed. Both of them occupy less memory than HashMap, but the retrieval time is slightly higher than HashMap. If the number of data items is less than 1000, there is no difference in their runtime.

  • Context Awareness

Activity memory is relatively easy to leak. Because they maintain all the view layers of the UI and occupy a large amount of space, their leakage is also very expensive ". Many operations require Context objects. You initiate an Activity. If the reference is cached and the object storage period is longer than that of your Activity, if the reference is not cleared, memory leakage occurs.

  • Avoid non-static internal class)

Create a non-static internal class and instantiate it to create an implicit reference to the external class. If an internal class instance takes longer time than an external class, the external class will be retained in the memory even if it is no longer needed. For example, in the Activity class, create a non-static class that extends AsyncTask, and start the asynchronous task to destroy the Activity when it is running. This asynchronous task keeps this Activity running during its running. The solution is not to do this. To do this, declare a static internal class.

2.4 GPU Profiling

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

On the GPU tab, you can view the time spent rendering each frame in a graphical manner on the screen. Each frame in the image represents a rendered frame. Color indicates different cycles of processes:

  • Painting (blue)

Indicates the View # onDraw () method. Create/change the DisplayList object and convert it to an OpenGL command that the GPU can understand. High bars may be complex view, but require more time to draw their display list, and many views will become invalid in a short time.

  • Preparation (purple)

Add another thread to Lollipop 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 send it to the GPU. In this way, the UI thread can start to process the next frame during rendering. At this time, the UI thread sends all resources to the RenderThread. This step may take a long time if there are many resources to pass (such as many/heavy display lists.

  • Processing (red)

Execute the display list to generate OpenGL commands. Because view re-painting is required, if many/complex display lists need to be converted, this step may take a long time. When a view is invalid or moved, you must re-paint the view.

  • Run (yellow)

Send OpenGL commands to GPU. Since the CPU sends these cached commands to the GPU and expects to clear the cache, the call is blocked. The number of caches is limited, and the GPU is also very busy-the CPU will find that you must wait for the cache to be released first. Therefore, if we see a high bar in this step, it may mean that the GPU is very busy drawing the UI, which is too complicated in a short time.

For detailed operation examples, see the original document.

2.5 Hierarchy Viewer

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

With Hierarchy Viewer, you can fully observe the screen view Hierarchy and attributes of all views. You can also export theme data to view all attributes of each style. However, this data can be viewed only when the Hierarchy Viewer runs independently. It cannot be viewed in the Android monitor.

The author uses this tool to design and optimize the layout.

The author believes that there is time to measure each view and all its subviews. Color indicates the comparison between the view and other views in the tree, and it is easy to find the weakest link. As we can preview the view, we can track and find the delete redundancy steps through the view tree. Among them, Overdraw has the biggest impact on performance.

2.6 Overdraw

If the GPU needs to draw a lot of content on the screen, it takes more time to draw each frame, so that the execution cycle is extended and displayed in yellow in the image. Overdraw occurs when a yellow button is drawn on a red background. In this case, the GPU needs to draw a red background first, and then draw a yellow button on it, Overdraw is inevitable. If there are too many Overdraw layers, this will overload the GPU and deviate from the goal of 16 Ms.

Set the "Debug GPU Overdraw" Developer option. The severity of all Overdraw is displayed in color. 1 ~ Twice the Overdraw is good, and even some small red areas are not bad. But if there is a lot of red on the screen, this is a problem. But they are all covered in red. This is the problem. The author suggests that only one color is used to set the background to solve this problem.

Note: The default theme declares the background color of a full screen window. If an Activity with an opaque layout overwrites the entire screen, you can delete the Overdraw layer by deleting the background color of the window.

Hierarchy Viewer can output all layers to the PSD file and open it in Photoshop. Studying different layers in Photoshop shows all Overdraw in the layout. Remove redundant Overdraw and strive to improve performance to blue.

2.7 Alpha

The use of transparent effects will also affect performance. Why?

ImageView overlaps with each other. Use setAlpha () to set the alpha value, which will be passed to all subviews to draw the frame buffer. The results are all overlapped. 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 the alpha value before being copied to the frame buffer. The effect is better. However, we have paid for this: Changing the "frame" buffer to the off-screen buffer actually adds an implicit Overdraw layer. The OS does not know the processing, so complex operations are often performed by default.

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

  • TextView

Use setTextColor () instead of setAlpha (). You can use the alpha channel of text color to draw text directly.

  • ImageView

Use setImageAlpha () instead of setAlpha (). The reason is the same as that of TextView.

  • Custom View

If a custom view does not support overwriting a view, this complex behavior is irrelevant. You can rewrite the hasOverlappingRendering () method to make it return false, and notify the OS to draw a custom view directly. You can also rewrite onSetAlpha () to get it to return true, select manual processing settings, and perform operations corresponding to each alpha value.

2.8 Hardware Acceleration

After hardware acceleration is introduced in Honeycomb (Honeycomb, Android 3.x), rendering apps on the screen can be performed with a new drawing model (http://developer.android.com/guide/topics/graphics/hardware-accel.html. The new model introduces the DisplayList structure to record view rendering and drawing commands. There is another good feature that is often ignored or incorrectly used by developers-view layer.

Using the view layer, we can render a view without a screen buffer (as we have seen before, using the alpha channel) and manipulate it as we wish. Because this feature allows you to draw complex animated views more quickly, it is mainly used for animation. Without these layers, the animation view will not work after changing the animation attributes (such as x coordinates, scaling, alpha values, and so on. For complex views, this ineffective effect is passed to all sub-views, and the re-painting cost is high. With hardware support, the GPU creates a texture for the view when the view layer is used. There are several operations that can be used for texture without damaging it, such as position X/Y, rotation, alpha, and so on. All means that during the animation, you can draw a complex animation view on the screen without damaging it at all. This makes the animation smoother.

It is suggested to remember several things when using the hardware layer:

  • Clear the view. The hardware layer consumes space and GPUs with limited storage components. So use (like animation) only when necessary and clear it afterwards.
  • If the view is changed after the hardware layer is used, the hardware layer is invalid and the view is repainted in a non-screen buffer zone. This happens when you change the properties that have no hardware-layer optimization (so far, optimization only: rotation, scaling, x/y, conversion, axis shifting, and alpha ).
3. Other materials

To illustrate performance analysis and optimization, the author prepares a lot of code to simulate the scenario. These codes can be found in Github code library (https://github.com/Udinic/PerformanceDemo) or Google Play (https://play.google.com/store/apps/details? Id = com. udinic. perfdemo. He puts different scenarios into different activities and writes documents to help you understand the problems encountered when using these activities as much as possible. You can use tools and run apps to read the javadoc of the Activity.

 

The author also recommends some learning and communication methods:

    • Learn how Android graphics architecture (http://source.android.com/devices/graphics/architecture.html) works. Here You Need To Know How Android renders everything about the UI and explains different system elements, such as SurfaceFlinger and how they interact with each other. This document is long but worth reading.
    • About Google I/O 2012 talk (https://www.youtube.com/watch? V = Q8m9sHdyXnE) to demonstrate how the drawing model works, and how/why there is a Jank in UI rendering.
    • The Android performance workshop (https://www.parleys.com/tutorial/part-2-android-performance-workshop), which starts from Devoxx 2013, shows some optimizations to the drawing model in Android 4.4 and demonstrates different performance optimization tools (Systrace, Overdraw, etc ).
    • A long article on preventive optimization (https://medium.com/google-developers/the-truth-about-preventative-optimizations-ccebadfd3eb5) illustrates why this is different from premature optimization. Because many developers think that the impact is not obvious, some of their code is not optimized. One thing to remember is that the accumulation of less is a big problem. If you have the opportunity to optimize a small part of the code, it may be minimal, and do not give up optimization.
    • Android memory management (https://www.youtube.com/watch? V = _ CruQY55HOk) This is an old Google IO 2011 video. It still makes sense. It shows how Android manages APP memory and how to use tools (such as Eclipse MAT) to identify problems.
    • Google Engineer Romain Guy's case analysis (http://www.curious-creature.com/docs/android-performance-case-study-1.html) on how to optimize the Twitter client. In this case analysis, Romain shows how he finds performance problems in the APP and how he suggested to modify them. In a reply, it shows other problems that occur after the same APP is re-designed.

The author hopes that everyone will have enough information and confidence. Optimize your APP from today!

 

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

 

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.