Android Interface Performance Tuning manual

Source: Internet
Author: User

The interface is the most critical part of the Android app that directly affects the user experience. If the code is not well implemented, the interface is prone to Dayton and causes the application to consume a lot of memory. Division I do this kind of ROM company is not the same, pre-installed applications must be very smooth, so that the first feeling to customers or users is fast. Also card and slow application experience, will affect customers or users of product confidence and evaluation, so can not be ignored.

I. Android rendering Knowledge 1.1 Drawing Principle

  
The Android system requires every frame to be drawn in 16ms, and a smooth completion of a frame means that any special frame needs to execute all the rendering code (including the framework sent to the GPU and the CPU draws to the buffer command) to be completed within 16MS to maintain a smooth experience. This speed allows the system to render at a smooth frame rate of about 60 frames per second (1 seconds/0.016 frames per second = 62.5 frames/second) during animation and input events.


  
If your app does not draw this frame within 16ms, assuming you've spent 24ms to draw this frame, you'll get dropped frames.


  
The system is ready to draw a new frame onto the screen, but this frame is not ready, and there is no drawing operation and the screen is not refreshed. Feedback to the user, is the user staring at the same picture to see the 32ms instead of 16ms, that is, the drop frame occurred.

1.2 Drop Frame

  
Dropping frames is a very central issue in the user experience. Discard the current frame, and can not continue after the previous frame rate, this discontinuous interval will be easy to attract the user's attention, that is, we often say that the lag, not smooth.
  
There are many reasons for dropping frames, such as:

    • Spend a lot of time redrawing most of the interface, which is a waste of CPU cycles;

    • Excessive drawing is severe, and it takes too much time to draw objects that the user cannot see;

    • There are a lot of animations repeated over and over, consuming CPU, GPU resources;

    • Frequent triggering of garbage collection;

1.3 Why is 60Fps?

Android requires each frame to be drawn in 16ms, then the 1-second frame rate is about 60 frames per second (1 seconds/0.016 frames per second = 62.5 frames/second), why should it be used as a measure of App performance? This is because collaboration between the human eye and the brain is not able to perceive more than a screen update.

Most Android devices on the market have a screen refresh rate of up to one HZ. Of course, exceeding the FPS is meaningless, the human eye does not perceive the difference. The FPS is a continuous linear movement that can be perceived by the human eye, so it is a common frame rate for the film's aprons, since this frame rate is sufficient to support the content of most movie images, while minimizing expense. However, below the FPS is not able to smooth performance of the beautiful picture content, it is necessary to use the FPS to achieve the desired effect.
  
The interface performance goal of the application is to maintain the FPS, which means that each frame you have only a 1 second (60 fps) time to handle all the tasks.

1.4 Garbage Collection

  
The garbage collector is a mechanism that automatically frees memory that is no longer referenced while the app is running, often called a GC. Frequent GC is also one of the culprits for serious performance problems.
As mentioned earlier, the smooth completion of a frame means that all render code must be completed within 16MS. Frequent GC can severely limit the amount of time remaining in a frame of time, and if the GC does more work than is necessary, the less time is left to apply the smoothed frame rate. The closer you get to 16ms, the easier it will be to cause the garbage collection event to trigger.
  
Note that Android4.4 introduced a new ART virtual machine to replace the Dalvik virtual machine. Their mechanisms are very different, in simple terms:

    • The GC of the Dalvik virtual machine is very resource-intensive, and in normal circumstances a good hardware performance of the Android device will also be easy to consume 10–20 ms time;
    • The GC of the art virtual machine dynamically boosts the efficiency of garbage collection and interrupts in art, typically between 2–3 Ms. There is a great performance improvement over the Dalvik virtual machine.
      ART virtual machines have a significant performance boost relative to garbage collection for Dalvik virtual machines, but 2–3 MS recovery time is sufficient for exceeding the 16ms frame rate limit. Therefore, although garbage collection is no longer a resource-intensive behavior after Android 5.0, it is always necessary to avoid it as much as possible, especially in the case of animations, which can lead to some dropped frames that make the user feel obvious. # # # * * 1.5 UI thread * *
      The UI thread is the main thread of the application, and many of the performance and lag issues are due to the amount of work we do in the main thread.
      Therefore, all resource-consuming operations, such as IO operations, network operations, SQL operations, list refreshes, etc., should be implemented in the background process, can not occupy the main thread, the main thread is the UI thread, is to keep the program smooth key;
      In Android 5.0, the Android framework layer introduced the "render Thread" for sending actual rendering operations to the GPU. This thread mitigates some of the UI thread's reduced operations. But input, scrolling, and animation are still in the UI thread, because thread must be able to respond to operations.
1.6 Vertical Synchronization

  
Vertical synchronization is a new technology introduced by Android4.1 through Project Butter in the UI architecture, with technologies such as Triple Buffer and Hwcomposer being introduced to improve the fluency of the UI.
  
For example, you took a picture, then rotated 5 degrees and then took another photo, cut the middle of the two photos together, and got:
This part of the middle has a distinctly different part, which is equivalent to the result of inconsistent device refresh rate and frame rate.
  
In general, the frame rate of the GPU should be higher than the refresh rate to not stutter or drop frames. If the screen refresh rate is faster than the frame rate, the screen will display the same screen in two frames, this intermittent situation continues to occur, the user will obviously feel the animation lag or drop frame, and then back to normal, we often call it splash screen, skip frame, delay. Applications should avoid these frame rate drops in order to ensure that the GPU can complete data acquisition and writing before the screen is refreshed, ensuring smooth animation.

1.7 UI drawing mechanism and rasterization

  
The vast majority of rendering operations rely on two hardware: CPU, GPU. The CPU is responsible for Measure, layout, Record, Execute compute operations, and the GPU is responsible for rasterization (rasterization) operations. Non-required view components can result in extra CPU compute operations and also consume extra GPU resources.
  
Rasterization (rasterization) splits resource components, such as Button, Shape, Path, Bitmap, into different pixels for display. This operation is time consuming, so the GPU is introduced to speed up rasterization operations.
  
The CPU is responsible for computing the UI components into polygons (polygons), textures (Texture), and then to the GPU for rasterization rendering, and then uploading the processing results to the on-screen display
  
The display of those resource components in Android (such as Bitmaps, drawable) is packaged together into a unified texture (Texture) and then passed to the GPU.
  
The display of the image is loaded into memory by the CPU's calculation and then passed on to the GPU for rendering. The text is displayed by the CPU converted to texture (Texture), then to the GPU for rendering, back to the CPU to draw a single character, and then re-reference GPU-rendered content. The display of animations is more complex, and we need to process all CPU and GPU calculations, drawing, rendering, etc. within MS to get the smooth experience of the app.

two. To detection and resolution 2.1 Detection Dimension   

Depending on the difference between the business and the required test granularity, there will be different detection dimensions. The interface performance detection dimensions that I currently need for my business are as follows:

    • Excessive drawing of interface (detection of excessive drawing)
    • Rendering performance, (Detection of UI rendering performance rendering in strict mode)
    • Rationality of layout boundary; (Rationality of detecting element display)
    • There are some user scenarios in the special test that may also contain other invisible detection dimensions, such as:
    • OpenGL tracking analysis;
    • The GPU view update is reasonable;
    • Flash hardware layer update rationality;
    • Animation acceleration/deceleration state problem point detection;
    • ......
2.2 Debugging Tools

  
Detecting and resolving interface performance issues is largely dependent on your application architecture, and fortunately, Andorid provides a lot of debugging tools, and it's important to know and learn how to use them, which can help us debug and analyze interface performance issues so that the application has a better performance experience. The following is a list of common Android interface performance Debugging tools:

2.2.1 Hierarchy View

  
Hierarchy view comes in the Android SDK and is often used to see if the view structure of the interface is too complex to understand which views are over-drawn and how to improve

2.2.2 Lint   

Lint is a static code scanning tool that comes with ADT, which provides improved recommendations for XML layout files and for unreasonable or risky modules in project code. The official tips on the actual use of Lint are listed below:

    • Contains useless branches, recommended removal;
    • Contains useless parent controls, recommended removal;
    • Warning the layout depth is too deep;
    • It is recommended to use compound drawables;
    • It is recommended to use the merge label;
2.2.3 Systrace

  
Systrace in Android DDMS, can be used to track graphics, view and window information, to find some deep-seated problems. Very troublesome, limited, practical debugging I basically do not use.

2.2.4 Track

  
Track in Android Ddms, is a great way to follow the construction of the view when the method of time-consuming, accurate to each function, whether it is applied functions or system functions, we can easily see the place of the drop frame and the frame of all the functions of the call situation, to find the problem point optimization.

2.2.5 Overdraw

  
By turning on "debug GPU over-Drawing" in the developer options of the Android device's settings app, you can view the over-rendering situation in all the interfaces and branches of the app, making it easy to optimize.

2.2.6 GPU Rendering mode analysis

  
By launching GPU rendering mode analysis in the developer options of the Android device's settings APP, you can get the time to render each frame of the last 128 frames, and analyze performance and performance bottlenecks for rendering.

2.2.7 Strictmode   

By launching "strict Mode" in the developer options of the Android device's settings app, you can see which actions are being applied too long on the main thread. When some actions violate strict mode, the perimeter of the screen flashes red, and the information about the Strictmode is output to the LOGCAT log.

2.2.8 Animator Duration Scale   

Speed up or slow down the animation by opening the Window animation zoom/Transition Animation scale/Animation program zoom in the developer options of the Android device's settings APP to see if there is a problem with the animation in the accelerated or slowed down state.

2.3 How to solve   

As mentioned above, our current required test dimensions are as follows:

    • Excessive drawing of interface (detection of excessive drawing)
    • rendering performance; (Detection of UI rendering performance in strict mode) The next step is to focus on these two points, from concepts, tracing, root causes, and troubleshooting tools, to explain how to solve them, and how to optimize recommendations for development.
three. Interface over-rendering (overdraw) 3.1 Over-drawing concepts

  
Over-drawing is a term that indicates that some components draw more than 1 times over a pixel on the screen.
  
In layman's terms, the drawing interface can be likened to a graffiti graffiti wall, graffiti is a lot of work, the wall of each point in the graffiti process may be painted a variety of colors, but the final color can only be 1 kinds. This means that we have to spend a lot of time in the process of graffiti, those non-final colors are not visible to the people, is a kind of waste, energy and resources, there is a lot of room for improvement. Drawing the interface in the same way, it takes too much time to draw the stacks of things that the user can't see, which is wasting CPU cycles and rendering time!
  
The official example is that the user-activated card is at the top, and those cards that are not activated below, spend too much time plotting objects that the user cannot see.

3.2 Tracking over-drawing

  
By turning on "debug GPU over-Drawing" in the developer options of the Android device's settings app, you can view the over-rendering situation in all the interfaces and branches of the app, making it easy to optimize.
  
Android displays different shades of color on the screen to indicate over-rendering:

    • No color: No over-drawing, that is, a pixel is drawn 1 times, showing the application of the original color;
    • Blue: 1 time times over drawn, that is, a pixel point is plotted 2 times;
    • Green: Twice times over drawn, that is, a pixel point is plotted 3 times;
    • Light red: 3 times times over drawn, that is, a pixel point is plotted 4 times;
    • Dark red: 4 times times over-drawn and above, that is, a pixel point is plotted 5 times and above; the hardware performance of the device is limited, and performance is reduced when excessive drawing causes the application to consume more resources (more than the available resources), and it behaves like stuttering, non-smooth, ANR, etc. To maximize the performance and experience of your application, you need to minimize over-drawing, which is more blue blocks than red blocks.
      The actual test, the following two points commonly used as over-drawn test indicators, the over-drawing control in a well-agreed reasonable range:
    • No more than 4X over-rendering (dark red area) for all interfaces and branch interfaces;
    • With all the interface and the branch interface, the 3X over-drawn total area (light red area) does not exceed 1/4 of the visible area of the screen;
3.3 Causes of excessive drawing

  
Over-rendering is largely the problem of overlapping views, followed by unnecessary background overlap.
  
Official examples, such as an application where all the view has a background, will look like the first picture, and after removing the unnecessary background (referring to the default background of window, the background of the layout, the text, and the possible background of the picture), the effect is like the second picture. There is basically no over-drawing situation.

3.4 The impact of unreasonable XML layout on drawing

  
The deeper the depth of the node tree of the layout file, the more labels and property settings in the XML, the more disastrous the display of the interface.
  
An interface to display, the first step will be parsed layout, after Requestlayout also a series of measure, layout, draw operation, if the layout file nested too deep, the label property has too bloated, each step of the execution time will be affected, The display of the interface is not displayed until these operations are performed, so the time for each step is increased and the final display time will be longer.

3.5 Source-related

  
Have the ability and interest to see the source of children's shoes, over-drawn source location in:/frameworks/base/libs/hwui/openglrenderer.cpp, interested can go to study to see.

Four. Rendering Performance (Rendering) 4.1 Rendering Performance Concepts

  
Rendering performance is often the culprit for dropping frames, a problem that is common and frustrating. Fortunately, Android gives us a powerful tool to help us track performance rendering problems very easily and see what is causing your application to stutter and drop frames.

4.2 Tracking Rendering Performance

  
Select "Show as bar on screen" by opening the "GPU Rendering mode Analysis" option in the developer options for Android device Settings APP.
  
This tool will display the GPU drawing data of the last 128 frames of the current interface in real time on the screen of the Android device, including StatusBar, NavBar, GPU drawing histogram data for the current interface. We generally only need to be concerned about the GPU drawing data of the current interface.
  
There are 128 small bars on the interface, representing the most recent 128-frame GPU drawing data for the current interface. A small histogram represents the time-consuming rendering of this frame, and the higher the histogram is, the longer it takes to take time. As the interface refreshes, the histogram information is also refreshed in real time.
  
There is a green line in the middle, the key to keeping the animation flowing is to keep the vertical bars below the green Line as far as possible, and you may lose one frame of content at any time than the Green Line.
  
Each bar chart is made up of three colors: blue, red, and yellow.

    • Blue represents the time this frame draws the Display List. In layman's terms, it is a record of how long it takes to update the view on the screen. In the code language, it is the OnDraw method that executes the view that creates or updates the time of the Display List for each view.
    • Red represents the time it takes for this frame of OpenGL to render the Display List. In layman's terms, it is time consuming to perform a view drawing. In the code language, it is the time for Android to render the Display List 2D with the API interface of OpenGL ES.
    • Yellow represents the time that the frame CPU waits for GPU processing. In layman's terms, the wait time for the CPU to wait for the GPU to send a reply to the command. In the code language, this is a blocking call.
      In the actual test, the following two points are commonly used as the test indicators for rendering performance, and the rendering performance is controlled within a reasonable range of conventions:
    • Perform all functions and branching functions of the application, and the bar area involved in the operation should be kept below the green line at least 90;
    • From the perspective of the user's physical examination, it is subjective to judge whether or not the feeling of Kaka in all operations is acceptable under the Android device with the memory of MB.
4.3 The root cause of poor rendering performance

  
When you see the Blue Line higher, it may be because your view suddenly fails to redraw, or the custom view is too complex to take too long.
  
When you see the red line higher, it may be because your view is resubmitted due to the need to redraw (such as the screen from the vertical screen rotated into a horizontal screen after the current interface re-created), or the custom view is very complex, it is cumbersome to draw, resulting in a long time. For example, the following view:
  
When you see the Yellow Line high, that means you're giving the GPU too much work, too much of the responsible view needs OpenGL commands to draw and process, causing the CPU to wait until the GPU sends a reply to the command.

4.4 Inspection Instructions

This tool is a great way to help you find rendering-related problems, help you find performance bottlenecks in your lag, and track what is causing the application to lag and slow, so you can optimize at the code level. Even let the person in charge of the product design improve his design to get a good user experience.
  
When rendering performance is detected, it is often accompanied by turning on strict mode to see which scenarios are being applied on the UI thread (the main thread) for too long execution time.
  
There are also some powerful but probably less-used tools that assist in analyzing when testing performance rendering, such as:

    • Hierarchyviewer: This tool is often used to see if the view structure of the interface is too complex to understand which views are over-drawn and how to make improvements;
    • Tracer for OpenGL: This tool collects all the drawing commands that the UI interface sends to the GPU. Often used to assist the developer in debugging, locating some difficult rendering details that hierarchyviewer tools cannot locate.
Five. Optimize Advice for the development interface 5.1 Structure of the optimized layout

  
The layout structure is too complex to slow down rendering, causing performance bottlenecks. We can optimize by following these idiomatic and effective layout principles:

    • avoid complex view hierarchies. The more complex the layout, the more prone to performance problems, finding the most resource-saving way to present nested content;
    • try to avoid using relative layout relativelayout at the top level of the view level. Relative layout relativelayout is more resource-intensive because a relative layout relativelayout requires two measurements to ensure that it handles all of the layout relationships, and this problem is accompanied by the increase in relative layout relativelayout in the view hierarchy. and become more serious; the
    • layout-level scenario suggests using linear layout linearlayout instead of relative layout relativelayout because the linear layout linearlayout performance is higher; you do need to lay out the branches relatively Relativelayout, you can consider a more optimized grid layout GridLayout, which has preprocessed the branch view relationship, avoids the problem of two measurements, and the relatively complex layout of
    • is recommended for relative layout relativelayout. Relative layout relativelayout can easily implement a layout that is linearlayout nested in a linear layout;
    • do not use absolute layout absolutelayout;
    • extracts reusable components and labels Reuse. If you apply a layout to a UI in multiple places, it is written as a layout part that is easy for each UI to reuse. The
    • uses the merge label to reduce the nesting level of the layout.
    • Remove the unwanted invisible background. There are multi-layered background color layout, only the top level of the user visible color, the other users can not see the underlying color to remove, reduce invalid drawing operations;
    • Avoid using the Layoutweight property as much as possible. Using a linear layout that contains the Layoutweight property linearlayout each subassembly needs to be measured two times and consumes too much system resources. This problem is especially important when using the ListView tag with the GridView label, because the subcomponents are created repeatedly. The split layout can be done using a 0DP view of the relative layout relativelayout, if not, then ...
    • The layout structure of a reasonable interface should be wide and shallow, rather than narrow and deep;
5.2 Optimizing processing logic
    • Load views on demand. Some of the less reusable views of resource consumption, can wait until the time needed to reload, improve UI rendering speed;
    • Use the viewstub tag to load some less commonly used layouts;
    • Dynamic inflation view performance is better than using Viewstub label setvisiblity performance, of course, some features of the implementation of Viewstub label more appropriate;
    • Try to avoid unnecessary resource operation and save valuable computing time;
    • Avoid heavy work on the UI thread. resource-intensive operations (such as IO operations, network operations, SQL operations, list refreshes, etc.) consume resources using the background process to implement, can not occupy the UI thread, the UI thread is the main thread, the main thread is the key to keep the program smooth, should only operate those core UI operations, such as processing view properties and drawing;
    • Minimize the wake-up mechanism. We often use broadcasts to receive messages and events that are expected to respond, but too much of the response exceeds our own requirements, which consumes the extra performance and resources of Android devices. Therefore, the wake-up mechanism should be minimized, and when the application does not care about these disappears and events, it turns off the broadcast and carefully chooses the Intent to respond to.
    • For low-end devices, such as 512M memory, dual-core CPUs, and low resolution, make sure your application can meet different levels of equipment.
    • Optimize your app's startup speed. As soon as the app launches an app, the interface's feedback display can give the user a good experience. For faster start-up, you can defer loading some UI and avoid initializing code at the application level of the app.
5.3 Use the DEBUG tool
    • Use some of the debugging tools provided by Android to track the performance of the main functions of the application;
    • Use some of the debugging tools provided by Android to track the memory allocation of the main functions of the application;

This article reproduced self-Listening cloud blog

Android Interface Performance Tuning manual

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.