Android Advanced Development's performance Optimization model _android

Source: Internet
Author: User
Tags data structures memory usage message queue pack try catch visibility

This chapter describes the performance aspects of the Android advanced development process. Mainly includes the electricity, the view, the memory three performance aspect knowledge point.

1. View Performance

(1) Overdraw Introduction

Overdraw is the excessive rendering, refers to in a frame of time (16.67MS) pixel has been plotted several times, theoretically a pixel is only one time to draw is optimal, but because the overlapping layout caused some pixels will be drawn more than once, And each drawing corresponds to the CPU of a set of drawing commands and some operations of the GPU, when this operation takes more than 16.67ms, there will be a drop frame phenomenon, performance for the application of cotton, so the overlapping invisible elements of the repeated rendering will incur additional overhead, need to minimize the occurrence of overdraw.

(2) Overdraw detection

Android offers the option to measure Overdraw, on the developer option-debugging GPU over drawing (show GPU Overdraw), opening options to see the status of the current page overdraw, so you can watch the drawing status of the screen. The tool uses three different colors to draw the screen to indicate where and how far the overdraw occurs:

• No color: means no overdraw. The pixel was only painted once.

• Blue: It means overdraw 1 time times. Pixel was drawn two times. Large blue is still acceptable (if the whole window is blue, you can get rid of the first layer).

• Green: means overdraw twice times. Pixel was drawn three times. Medium-sized green areas are acceptable but you should try to optimize and reduce them.

• Reddish: means overdraw 3 times times. The pixel is drawn four times, and the small range is acceptable.

• Dark red: means overdraw 4 times times. The pixel is plotted five times or more. This is wrong, to fix them.

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 choice of control container

The layout controls provided by Android mainly include LinearLayout, Tablelayout, Framelayout, and Relativelayout. The same interface can be expressed using different container controls, but each container control describes the complexity of the interface differently. Generally to linearlayout the most easy, relativelayout more complex. LinearLayout can only be used to describe a continuous array of controls in one direction, while Relativelayout is almost used to describe an interface with arbitrary complexity. To sum up: linearlayout easy to use, high efficiency, limited expression ability. Relativelayout complex, expressive ability, low efficiency. From the point of view of reducing overdraw, linearlayout will increase the level of the number of controls, naturally relativelayout more excellent, However, LinearLayout is preferred when an interface uses LinearLayout and does not bring more control numbers and control levels than relativelayout.

2 Remove window default background

When you use some of the themes that come with Android, Windows defaults to adding a solid background that is held by Decorview. When a custom layout adds a background image or sets the background color, then the decorview background is useless at this time, but it produces a overdraw, resulting in a loss of rendering performance. Removing the background of window can call GetWindow () after Setcontentview () in OnCreate (), setbackgrounddrawable (null), or add Android to theme: Windowbackground= "null".

3 Remove other unnecessary background

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

4 Custom View Processing

For custom view views, you can use Canvas.cliprect () to help the system identify those areas that are visible. This method can specify a rectangular area that will be drawn only within the region, and other areas will be ignored. This API can be a good help for custom view that has multiple sets of overlapping components to control which areas are displayed. At the same time, the Cliprect method can also help to save CPU and GPU resources, the drawing instructions outside the Cliprect area will not be executed, and those parts in the rectangular area will still be drawn. In addition to the Cliprect method, we can also use Canvas.quickreject () to determine whether a rectangle is not intersected, skipping the drawing operations within the rectangular area.

5) viewstub Efficient placeholder

When this happens, the runtime dynamically determines which view or layout to display according to the criteria. The common practice is to write the View on top, first set their visibility to view.gone, and then dynamically change its visibility in the code. The disadvantage of this pattern is that it consumes resources. Although the view of the initial view.gone but in the inflate layout of the view will still be inflate, the program will still create objects, will be instantiated, will be set properties, consumes memory and other resources.

The recommended practice is to use android.view.viewstub,viewstub to be a lightweight view, which is an invisible control that does not occupy the location of the layout and occupies a very small resource. You can specify a layout for viewstub, and only viewstub will be initialized when inflate layout, and then when Viewstub is set to be visible, or when viewstub.inflate () is invoked, The layout of the viewstub is inflate and instantiated, and then the Viewstub layout property is passed to the layout it points to. In this way, you can use viewstub to make it easy to show a layout at run time or not.

6) Use of Draw9patch

Add a border to ImageView, usually after ImageView set a background map, exposing the border is perfect to solve the problem, at this time this imageview, set up a two-layer drawable, two layers of drawable overlapping area to draw two times, leading to Overdraw. Optimization scenario: Make the background drawable into Draw9patch, and set the portion of the foreground overlay to transparent. Because the Android 2D renderer optimizes the transparent area in the Draw9patch, it optimizes the overdraw.

7) Merge

Use the merge label to make a container control. 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 line. 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, then there is an extra layer of nesting that is not used, which will undoubtedly slow 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 recovery

The Dalvik heap of 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 cap on it.

Logically speaking, the size of the heap and the amount of memory used in the actual physical sense are not equal, proportional Set Size (PSS) records the memory that the application itself occupies and shares with other processes.

The Android system does not defragment the free memory areas in the heap. The system simply determines whether the end of the heap has enough space before the new memory allocation, and if not enough space triggers the GC operation, freeing up more free memory space. In the advanced system version of Android, there is a generational Heap memory model for HEAP space, and the most recently allocated objects are stored in the young generation area. When the object stays in the area for a certain amount of time, it is moved to the old Generation, which accumulates a certain amount of time and then moves to the permanent Generation area. The system performs separate GC operations based on different memory data types in memory. For example, objects that are just assigned to the young generation area are often more easily destroyed and recycled, while GC operations in the young generation area are faster than GC operations in the old generation region (as shown in Figure 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 operation 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 to be stored (as shown in Figure 2).

Fig. 2 Object value near threshold triggers GC operation

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

(2) Memory test plugin

1) leakcanary Introduction

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

2) Leakcanary Working principle

Refwatcher.watch () creates an object keyedweakreference to the north for monitoring.

• Next, detect if 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 into a. hprof file into the mobile phone system.

Heapanalyzerservice is started in another separate process, using Heapanalyzer parsing heap memory through haha this project

Heapanalyzer calculates that the shortest strong reference path to GC roots Determines whether leak occurs, and then establishes a chain of references that lead to leaks. The results are uploaded back to the Displayleakservice of the application process and a leaked notification is displayed.

(3) Memory optimization

1) cautious use of large heap

The 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. The available heap size of the application can be obtained by calling Getmemoryclass () at design time. In some special situations, you can declare a larger heap space for the application by adding the Largeheap=true attribute under the Manifest Application tab. You can then get to this larger heap size threshold by Getlargememoryclass ().

However, declaring a larger heap threshold is intended for a small number of applications that consume a large amount of RAM (for example, an editing application for a large image). Don't easily ask for a large heap size because you need to use more memory. Use large heap only when you know exactly where to use a lot of memory and why the memory must be kept. 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 to consider the device memory threshold and other factors to design the appropriate cache size

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

• How much memory space is left in the application?

• How many pictures will be presented to the screen at once? How many pictures need to be cached in advance so that they can be immediately displayed to the screen when they are fast sliding?

• What is the screen size and density of the device? A xhdpi device would need a larger cache than the hdpi to hold the same number of pictures.

• What is the size and configuration of the different pages for the bitmap design, and how much memory will be spent?

• How often does the page picture get accessed? Is there a part of it that is more frequently accessed than other pictures? If so, maybe you want to save the most frequently accessed memory, or set up multiple LRUCache containers for different groups of bitmaps (grouped by Access frequency).

3) resource files need to select the appropriate folder for storage

HDPI/XHDPI/XXHDPI, and so on, the pictures under different DPI folders will be processed by scale on different devices. For example, we only put a picture of 100100 in the hdpi directory, then according to the conversion relationship, XXHDPI's mobile phone to quote that picture will be stretched to 200200. It should be noted that in this case the memory footprint is significantly increased. For pictures that you don't want to be stretched, you need to put them in a assets or nodpi directory.

4 Try Catch some large memory allocation operations

In some cases, we need to evaluate in advance those code that may occur oom, and for these potentially oom code, add a catch mechanism to consider attempting a degraded memory allocation operation in the catch. For example, when Decode bitmap, catch to Oom, you can try to increase the proportion of the sample after another, try decode again.

5 cautious use of static objects

Because the static lifecycle is too long and consistent with the application process, improper use is likely to cause an object leak, and the static object should be used sparingly in Android.

6) Special attention to the unreasonable holding of the single Case object

Although the single case model is simple and practical, it provides a lot of convenience, but because the life cycle and application of the single case are consistent, it is easy to use unreasonable to have the leak of the holding 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 a stop state. Also note the memory leaks that are caused by the failure to stop the service after the service completes the task. When you start a service, the system tends to keep the service in the process of keeping the service. 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 hold into the LRU cache, which can affect the efficiency of switching between applications, and can even lead to unstable system memory usage, which will prevent all currently running service. It is recommended to use Intentservice, which will end itself as soon as possible after processing the tasks assigned 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 amount of memory needed to mapping code.

9 use more lightweight data structures

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

HashMap containers, compared to Android's arraymap containers for mobile operating systems, are in most cases inefficient and more memory-efficient. The usual HASHMAP implementation 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 automatic boxing of key and value (autoboxing) and avoid boxed unpacking.

10 avoid using enum in Android

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

11 Reduce the memory footprint of the bitmap object

Bitmap is a very easy to consume memory of the big fat, reduce the created bitmap memory footprint is the most important, usually have the following 2 measures:
insamplesize: Scaling, before loading the picture into memory, we need to figure out a suitable scaling ratio to avoid unnecessary large image loading.
decode Format: Decoding format, choose Argb_8888/rbg_565/argb_4444/alpha_8, there is a big difference.

12 Use smaller picture

When it comes to resource pictures, we need to pay special attention to whether there is room for compression in this picture, and whether you can use smaller pictures. Trying to use smaller pictures can not only reduce the use of memory, but also avoid a large number of inflationexception. Assuming that a large picture is referenced directly by an XML file, it is likely that the inflationexception will occur due to insufficient memory when initializing the view, and the root cause of this problem is oom.

13 Reuse of Memory objects

Most objects are reused, the final implementation of the scheme is the use of object pooling technology, or in the writing code explicitly in the program to create object pool, and then handle the reuse of the implementation logic. Or the use of some of the existing reuse features of the system framework to reduce the duplication of the creation of objects, thereby reducing memory allocation and recovery.

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, 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 to reduce the cost of memory, reusability better. But it's also important to keep an eye on the version of the Android system, for those different versions of the system that are very different, do not meet the requirements, or need to be built into the application itself.

15) Notice whether the cursor object is closed in time

In the program we often query the operation of the database, but often there will be careless use of cursor after the failure to close in a timely manner. These cursor leaks, repeated occurrences will have a great negative impact on memory management, we need to keep in mind the cursor object in time to close.

16 avoid the creation of objects in the OnDraw method

Similar to OnDraw, such as frequently called methods, must be careful to avoid the creation of objects here, because he will quickly increase the use of memory, and can easily cause frequent GC, or even memory jitter.

StringBuilder)

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

18 attention to the release of activity

In general, an activity leak is the most serious problem in a memory leak, it occupies a lot of memory and has a wide range of effects, requiring special attention to activity leaks due to the following two scenarios:

• Internal class references lead to the release of activity

The most typical scenario is an activity leak caused by handler, which can cause a leak of activity because handler continues execution if there is a delay in the handler task or if the queue is too long for execution. The chain of reference relationships at this point is the Looper-> MessageQueue-> message-> Handler activity. To solve this problem, you can perform the messages and Runnable objects in the Remove handler message queue before the UI exits. Alternatively, a static + WeakReference method is used to achieve the purpose of disconnecting the handler from the activity that has a referential relationship.

The activity context is passed to other instances, which can cause a leak to be referenced by itself.

The leakage caused by the internal class will not only occur on the activity, but any other internal class appears, it needs special attention! You can consider using a static type of inner class as much as possible, while using the weakreference mechanism to avoid leaks that occur because of cross-references.

19 Consider using the application context rather than the

For most situations where it is not necessary to use the context of the activity (which must be the activity contexts), you can consider using the application rather than the dialog of the activity, This will avoid inadvertent activity leaks.

(3) Electric power optimization

Electricity is actually one of the most valuable resources of handheld devices, and most devices need to be recharged to keep them going. Unfortunately, for developers, power optimization is the last thing they think about. But it is certain that you must not make your application a big drain.

Some of the following measures can significantly reduce the consumption of electricity:

• We should try to minimize the number of wake-up screens and duration, use Wakelock to deal with wake-up problems, be able to perform wake-up actions correctly, and turn off the operation in a timely manner to sleep.
• Some operations that do not have to be performed immediately, such as uploading songs, image processing, etc., can wait until the device is in a charging state or when the battery is sufficient.
• The operation that triggers the network request, each time will keep the wireless signal for a period of time, we can pack the fragmented network request to do one operation, avoids excessive wireless signal to cause the electricity consumption. About the power consumption of a wireless signal caused by a network request.

1 power consumption of several main reasons, functions

• Large amount of data network transmission (network)

• Continuous network switching (network)

• Parse large amounts of data (CPU)

2 about the optimization of the network

• Check the network connection before requesting the network. No network connection not requested

• Determine the type of network to request for specific data on a particular network. For example: When a large amount of data is transmitted, requests are on WiFi. WiFi Download data consumption is only 2, 3, 4G of 1/3.

• Use analytical tools that are highly efficient. According to the size of the specific business data, select the appropriate analytical tool. For example, the protocol resolution above Android typically recommends JSON.

• Download data using gzip compression to reduce network traffic and shorten download time

• Reasonable use of caching to avoid repetitive operations

• Use push instead of circular request

• The operation that triggers the network request, each time will keep the wireless signal for a period of time, we can pack the fragmented network request to do one operation, avoids excessive wireless signal to cause the electricity consumption.

• It's what the Jobscheduler API does. It combines the ideal wake-up time based on current situations and tasks, such as when charging or connecting to WiFi, or concentrating on tasks. We can use this API to implement a lot of free scheduling algorithms.

3) Electric Power optimization strategy

• Check all wake-up locks for redundancy or unwanted locations.

• Centralize relevant data requests and send them uniformly; Streamline data and reduce the transfer of unwanted data.

• Non-critical operations such as analysis and statistics, which can be done in the case of adequate or connected WiFi, refer to Jobscheduler.

• Streamline redundant services (service) to avoid time-consuming power consumption operations.

• Attention to the acquisition of positioning information, the use of timely closure.

The above is a small set to introduce the Android advanced development of the performance optimization model of the relevant knowledge, I hope that we have help in, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.