Android Performance optimization

Source: Internet
Author: User
Tags message queue try catch

This chapter describes performance-related processing in advanced Android development. Mainly includes power, view, memory three performance aspects of knowledge points.

1. View performance (1) overdraw Introduction

Overdraw is over-drawn, refers to a frame of time (16.67ms) pixels are drawn several times, in theory, one pixel is best to draw once at a time, but because the overlapping layout causes some pixels to be drawn multiple times, And each draw will correspond to a set of CPU drawing commands and GPU operations, when the operation takes more than 16.67ms, there will be a drop frame phenomenon, performance as the application of the lag, so the overlapping of the invisible elements of the repeated drawing will incur additional overhead, need to minimize the occurrence of overdraw.

(2) Overdraw detection

Android provides the option to measure Overdraw, in the developer Options-debug GPU over-draw (Show GPU Overdraw), open the option to see the status of the current page overdraw, you can observe the drawing state of the screen. The tool draws a screen with three different colors to indicate where and how overdraw occurred, where:

    • No color: Means no overdraw. Pixels are drawn only once.
    • Blue: means Overdraw 1 time times. The pixel was drawn two times. Large blue is still acceptable (if the whole window is blue, you can get rid of one layer).
    • Green: It means twice times the overdraw. The pixel was drawn three times. Medium-sized green areas are acceptable, but you should try to optimize and reduce them.
    • Light red: means Overdraw 3 times times. The pixel is drawn four times, and the small range is acceptable.
    • Dull red: it means 4 times times the overdraw. Pixels are plotted five or more times. This is wrong to fix them.

To improve the performance of the program in view, the general principle is: try to avoid overlapping invisible elements of the drawing.

(3) Overdraw Improvement 1) Reasonable selection of control container

The layout controls provided by Android mainly include LinearLayout, Tablelayout, Framelayout, Relativelayout. The same interface can be expressed using different container controls, but the complexity of each container control's description interface is not the same. General to linearlayout the most easy, relativelayout more complex. LinearLayout can only be used to describe a continuous arrangement of controls in one direction, and relativelayout can be used almost to describe an interface of any complexity. In summary: LinearLayout easy to use, high efficiency, limited expression capacity. Relativelayout complex, strong expression ability, low efficiency. From the point of view of reducing overdraw, linearlayout will increase the number of controls, naturally relativelayout better, However, LinearLayout is preferred when an interface uses LinearLayout and does not bring more control and control levels than relativelayout.

2) Remove window's default background

When using some themes from Android, window will be added by default to a solid color background, which is held by Decorview. When a custom layout is added with a background map or background color set, then Decorview's background is useless at this time, but it produces a overdraw, which results in a loss of drawing performance. Removing the background of window can call GetWindow () setbackgrounddrawable () after Setcontentview () in OnCreate () or add Android to theme: Windowbackground= "null".

3) Remove other unnecessary background

If the parent container has a background, do not set the background of the corresponding child control, and the large layout background has been set, you should avoid setting the background of the local repetition.

4) Custom View processing

For a custom view view, you can use Canvas.cliprect () to help the system identify those areas that are visible. This method allows you to specify a rectangular area that will be drawn only within this area, and other areas will be ignored. This API can be very helpful for those custom view that has multiple sets of overlapping components to control the displayed area. While the Cliprect method can also help conserve CPU and GPU resources, drawing instructions outside of the Cliprect area will not be executed, and components that are part of the content within the rectangular region will still be drawn. In addition to the Cliprect method, we can also use Canvas.quickreject () to determine if a rectangle is not intersected, skipping the drawing operations in the non-rectangular areas.

5) Viewstub High-efficiency placeholder

When this happens, the runtime dynamically determines which view or layout to display, depending on the condition. The common practice is to write the View on top, set their visibility to view.gone, and then dynamically change its visibility in the code. The disadvantage of this model is that it consumes resources. Although the initial view.gone of the view will still be inflate in the inflate layout, the object will still be created when the program is run, it will be instantiated, the properties will be set, and the memory resources will be consumed.

The recommended practice is to use android.view.viewstub,viewstub to be a lightweight view, an invisible, non-occupying layout location that occupies very small resources of the control. You can specify a layout for viewstub, in inflate layout, only viewstub is initialized, and when Viewstub is set to visible, or when viewstub.inflate () is called, The layout viewstub is inflate and instantiated, and the layout properties of the Viewstub are passed to the layout that it points to. In this way, you can use viewstub to make it easier to run, or not to display a layout.

6) Use Draw9patch

Add a border to ImageView, usually set a background map behind the ImageView, revealing the border to solve the problem, at this time, the ImageView, set two layers of drawable, two layers of drawable overlap area to draw two times, resulting in overdraw. Optimization scenario: Make the background drawable into Draw9patch, and set the part that overlaps the foreground to transparent. This overdraw is optimized because Android's 2D renderer optimizes the transparent areas in the Draw9patch.

7) Merge

Use the Merge tab to make container controls. The first seed view does not need to specify any layout properties for the parent view, that is, the parent container is just a container, and the child view needs to be added directly to the parent view for display on the row. The other is that if you need to embed a layout (or view) inside the LinearLayout, and the root node of the layout (or view) is also linearlayout, so that there is a layer of unused nesting, it is no doubt that this only slows down the program speed. And this time, if we use the merge root tag, we can avoid that problem.

2. Memory performance (1) Memory allocation and recycling

The Dalvik heap for each process reflects the footprint of using memory. This is the usual logical reference to the Dalvik Heap Size, which can grow as needed, but the growth behavior has a system that sets the upper limit for it.

The logical heap size and the actual physical sense of memory used are not equal, proportional Set size (PSS) records the application itself and the memory shared with other processes.

The Android system does not defragment the free memory area in the heap. The system will only determine if the remaining space on the end of the heap is sufficient before the new memory allocation, and if the space is insufficient, it will trigger the GC operation, freeing up more free memory space. In Android's advanced system version there is a generational heap memory model for the heap space, and recently allocated objects are stored in the young generation region. When the object stays in the area for a certain amount of time, it is moved to the old Generation, and finally accumulates a certain amount of time to move to the permanent Generation area. The system performs different GC operations based on the different memory data types in memory. For example, objects just assigned to the young generation area are usually more likely to be destroyed and recycled, while GC operations in the young generation region are faster than GC operations in the old generation region (1).

Figure 1 Performing different GC operations based on different memory data types

Each generation memory area has a fixed size. As new objects are assigned to this area, the GC action is triggered when the total size of the object approaches the threshold of this level of memory area to make room for other new objects (as shown in 2).

Figure 2 Object value Proximity threshold triggering GC operation

Typically, when a GC occurs, all threads are paused. The time it takes to perform a GC is also related to which generation it occurs, and every GC operation time in young generation is the shortest, old generation second, Permanent generation the longest. The length of execution is also related to the number of objects in the current generation, and it is much slower to traverse a tree structure to find 20,000 objects than to traverse 50 objects.

(2) Memory test plug-in 1) leakcanary introduction

Leakcanary is a tool for detecting memory leaks that can be used in Java and Android, and is contributed by the well-known open source organization Square.

2) Leakcanary Working principle
    • Refwatcher.watch () creates a keyedweakreference-to-North monitoring object.
    • Next, it detects whether the reference is cleared in the background thread, and if not, the GC will be triggered.
    • If the reference is still not cleared, dump the heap memory to a. hprof file and store it in the phone system.
    • Heapanalyzerservice is started in a separate process, using Heapanalyzer to parse the heap memory through haha this project
    • Heapanalyzer calculates the shortest strong reference path to the GC roots to determine if leak occurs, and then establishes a reference chain that causes the leak. The results are passed back to the displayleakservice of the application process, and a leaked notification is displayed.
(3) Memory optimization 1) use large heap sparingly

Android devices have different sizes of memory space depending on the hardware and software settings, and they set a different size heap limit threshold for the application. You can get the available heap size for your app by calling Getmemoryclass () at design time. In some special scenarios, you can declare a larger heap space for your app by adding Largeheap=true properties under the Application tab of manifest. You can then get to this larger heap size threshold by Getlargememoryclass ().

However, the claim for a larger heap threshold is intended for a small number of applications that consume large amounts of RAM (such as an editing application for a large picture). Don't be so easy because you need to use more memory to request a large heap size. Use the large heap only when you know exactly where to use a lot of memory and know why the memory must be preserved. Therefore, use the large heap property with caution. The use of additional memory space affects the overall user experience of the system and makes the GC run longer each time.

2) Consider the device memory threshold and other factors to design the appropriate cache size

For example, when designing the bitmap LRU cache for a ListView or GridView, the points to consider are:

    • How much memory space does the application have left?
    • How many images will be rendered to the screen at once? How many images need to be cached in advance so that they can be instantly displayed to the screen when quickly sliding?
    • What is the screen size and density of the device? A xhdpi device will require a larger cache than hdpi to hold the same number of images.
    • What is the size and configuration of the different pages for bitmap design, and how much memory will probably be spent?
    • How often is the page image accessed? Is there a part of it that is more frequent than other pictures with higher access? If so, you might want to save those most frequently accessed into memory, or set up multiple LRUCache containers for different groups of bitmaps (grouped by frequency of access).
3) resource files need to select the appropriate folder for storage

hdpi/xhdpi/xxhdpi the pictures under different DPI folders will be processed by scale on different devices. For example, we only placed a picture of 100100 in the hdpi directory, then according to the conversion relationship, XXHDPI's mobile phone to refer to the image will be stretched to 200200. It is important to note that in this case, memory consumption is significantly increased. For images that do not want to be stretched, they need to be placed in the assets or nodpi directory.

4) Try catch operation of some large memory allocations

In some cases, we need to evaluate the code that may have oom in advance, and for these potentially oom code, join the catch mechanism and consider trying a degraded memory allocation operation in the catch. For example decode bitmap, catch to Oom, you can try to increase the sampling ratio by one more times, try to decode again.

5) Use static objects with caution

Because static life cycles are too long and consistent with the application process, improper use is likely to cause object leaks, and static objects should be used with caution in Android.

6) Pay special attention to the unreasonable holding of the single Case object

Although the singleton pattern is simple and practical, it offers many conveniences, but because the life cycle of the singleton is consistent with the application, it is very easy to use the leakage of the object.

7) Cherish Services Resources

The application needs to use the service in the background, unless it is triggered and performs a task, otherwise the service should be in a stopped state. It is also important to note the memory leaks caused by stopping service failures after the service completes the task. When you start a service, the system tends to retain the service and keep the process in place. This makes the process expensive to run because the system has no way to free up the RAM space occupied by the service to other components, and the service cannot be paged out. This reduces the number of processes that the system can store into the LRU cache, which can affect the efficiency of switching between applications, and may even cause system memory usage to be unstable, thus failing to maintain all currently running service. It is recommended to use Intentservice, which will end itself as soon as possible after handling the tasks that have been confessed to it.

8) Use Proguard to remove unwanted code

Proguard can compress, optimize, and confuse code by removing unwanted code, renaming classes, domains and methods, and so on. Using Proguard can make your code more compact, which reduces the memory space required for mapping code.

9) Use more lightweight data structures

Consider using traditional data structures such as Arraymap/sparsearray rather than hashmap.

HashMap's containers, in most cases, show inefficiencies and make up memory compared to Android's Arraymap containers written specifically for mobile operating systems. The usual implementation of HashMap consumes more memory because it requires an additional instance object to record the mapping operation. In addition, Sparsearray is more efficient in that they avoid the automatic boxing of key and value (autoboxing), and avoid the boxed unpacking.

10) Avoid using enum in Android

The official Android training course mentions "Enums often require more than twice as much memory as static constants. You should strictly avoid use enums on Android. "For specific principles, please refer to" Android Performance Optimization Model (iii) ", so please avoid using the enumeration in Android.

11) Reduce memory consumption of bitmap objects

Bitmap is an extremely easy to consume memory of the big fat, reduce the amount of memory created by bitmap is the most important, usually has the following 2 measures:

    • Insamplesize: Scaling, before loading the image into memory, we need to calculate an appropriate scale to avoid unnecessary large image loading.
    • Decode format: Decoding formats, select Argb_8888/rbg_565/argb_4444/alpha_8, there is a big difference.
12) Use smaller images

When it comes to giving a picture of a resource, we need to pay special attention to whether the image has a space that can be compressed, or if it can use a smaller image. Using smaller images as much as possible will not only reduce the use of memory, but also avoid a lot of inflationexception. Given that a large picture is directly referenced by an XML file, it is possible that the root cause of the problem is an oom when initializing the view inflationexception due to insufficient memory.

13) Re-use of memory objects

Most of the reuse of objects, the final implementation of the scheme is to take advantage of the object pool technology, or to write code explicitly in the program to create an object pool, and then handle the reuse of the implementation logic. It is either to use some of the existing reuse features of the system framework to reduce the duplication of object creation, thus reducing the allocation and recycling of memory.

14) Reuse of the system's own resources

The Android system itself has a lot of resources built into it, such as strings, colors, pictures, animations, styles, and simple layouts, all of which can be referenced directly in the application. This will not only reduce the application's own load, reduce the size of the APK, but also to a certain extent, reduce the cost of memory, reusability is better. However, it is also important to keep an eye on the version differences of the Android system, whether there is a big difference in the performance of the different system versions, does not meet the requirements, or needs to be built into the application itself.

15) Note whether the cursor object is closed in time

In the program we often do the query database operation, but there are often inadvertently use the cursor after the case is not closed in a timely manner. These cursor leaks, repeated occurrences of the words will have a great negative impact on memory management, we need to remember to close the cursor object in a timely manner.

- ) to avoid OnDraw method inside the execution object is created

Similar to the frequent call method such as OnDraw, it is important to avoid doing the creation of objects here, because he will quickly increase the use of memory, but also easily caused by frequent GC, or even memory jitter.

- ) StringBuilder

In some cases, the code will need to use a large number of string concatenation operations, it is necessary to consider the use of StringBuilder to replace the frequent "+".

18) Be aware of activity leaks

In general, the leakage of activity is the most serious problem in memory leak, it occupies a lot of memory, the impact of a wide range, you need to pay special attention to the following two situations caused by activity leaks:

    • Internal class references result in activity leaks

The most typical scenario is an activity leak caused by handler, and if there are deferred tasks in handler or if the queue of tasks waiting to be executed is too long, it is possible that the activity will leak because handler continues to execute. The reference chain at this time is Activity, Handler, Message, MessageQueue, Looper. To solve this problem, you can execute the message in the Remove handler message queue with the Runnable object before the UI exits. or use static + WeakReference to achieve a referential relationship between the disconnected handler and the activity.

    • Activity context is passed to other instances, which can cause itself to be referenced and leak.

Internal classes are caused by leaks that occur not only in the activity, but in any other internal class where there is a need for special attention! Consider using the internal classes of the static type as much as possible, while using the weakreference mechanism to avoid leaks that occur because of mutual references.

19) Consider using application context instead of activity context

For most situations where the activity context is not required (the context of dialog must be the activity context), you can consider using application context instead of the activity context, This will avoid inadvertent activity leaks.

(3) Power optimization

Power is actually one of the most valuable resources in handheld devices, and most devices need to be recharged continuously to maintain their use. Unfortunately, for developers, power optimization is the last thing they'll think about. But you can be sure that you can't make your application a big drain on your battery.

There are several measures that can significantly reduce the consumption of electricity:

    • We should try to reduce the number of wake-up screens and duration, use Wakelock to handle wake-up problems, be able to perform wake-up operations correctly, and close the operation to sleep according to the set-up time.
    • Some actions that do not have to be performed immediately, such as uploading songs, picture processing, etc., can wait until the device is charging or has sufficient power.
    • Triggering the operation of the network request, each time will keep the wireless signal for a period of time, we can package the fragmented network requests for one operation, to avoid excessive wireless signal caused by the power consumption. About the power consumption of wireless signals caused by network requests.
1) Several main causes and functions of power consumption
    • Network transmission of large amounts of data (network)
    • Non-stop network switching (network)
    • Parsing large amounts of data (CPU)
2) About network optimization
    • Before network requests, check the network connection. No network connection is not requested
    • Determine the type of network that is requested for specific data under a specific network. For example: When a large amount of data is transferred, request it under WiFi. WiFi Download data consumption is only 2, 3, 4G 1/3.
    • Use high-efficiency parsing tools. Select the appropriate parsing tool based on the size of the specific business data. For example, the protocol resolution above Android generally recommends JSON.
    • Use gzip compression to download data, reduce network traffic, and shorten download times
    • Use caching wisely to avoid repetitive operations
    • Use push instead of loop request
    • Triggering the operation of the network request, each time will keep the wireless signal for a period of time, we can package the fragmented network requests for one operation, to avoid excessive wireless signal caused by the power consumption.
    • is what the Jobscheduler API does. It combines the ideal wake-up time based on the current situation and task, such as when you are charging or connecting to WiFi, or when the task is centralized. We can implement many free scheduling algorithms through this API.
3) Power optimization strategy
    • Check all wake-up locks for redundancy or useless locations.
    • Centralize relevant data requests and send them uniformly; Streamline data and reduce the transfer of useless data.
    • Non-essential operations, such as analysis and statistics, can be performed when the battery is fully charged or connected to WiFi, refer to Jobscheduler.
    • Streamline redundant services (service) to avoid power consumption for long periods of time.
    • Pay attention to the acquisition of location information and close it immediately after use.

Android Performance optimization

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.