Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - What is the focus of Android performance optimization?
What is the focus of Android performance optimization?
I. Summary:

This paper mainly discusses the performance optimization of Android from the aspects of rendering mechanism, UI optimization, multithreading, caching, power consumption optimization, code specification and so on.

Second, the optimization of rendering mechanism:

Most users think that the main source of performance problems such as stuck is rendering performance.

Android system sends out a VSYNC signal every 16ms, which triggers UI rendering. If each rendering is successful, you can achieve the 60fps required for a smooth picture. In order to reach 60fps, this means that most operations of the program must be completed within16 ms. ..

If one of your operations takes 24ms and the system can't render normally when it gets the VSYNC signal, then there will be frame loss. Then the user will see the same frame within 32 milliseconds.

Probably: It may be because your layout is too complicated to render in 16ms, it may be because there are too many drawing units in your UI, or it may be because the animation is executed too many times. These will lead to CPU or GPU overload.

Solved: We can use some tools to locate the problem. For example, we can use the HierarchyViewer to find out whether the layout in the activity is too complicated, or we can use the developer option in the mobile phone settings to open and display options such as GPU Overdraw to observe.

You can also use TraceView to observe the execution of CPU and find the performance bottleneck faster.

On overdraft:

Overdraw describes that a pixel on the screen is drawn many times in the same frame. In the multi-level UI structure, if the invisible UI is also being drawn, this will cause some pixel areas to be drawn many times. This wastes a lot of CPU and GPU resources. ?

Tips: We can open the option of displaying GPU overdraft through the developer option in the mobile phone settings, and we can observe the overdraft on the UI.

Illustration: Blue, light green, light red and deep red represent four different levels of overdraft. Our goal is to minimize the red overdraft and see more blue areas.

Tips: Sometimes overdraft is due to a large number of overlapping parts in your UI layout, and sometimes it is due to unnecessary overlapping backgrounds. For example, an activity has a background, and then the layout in it has its own background, while the applet has its own background.

Just by removing unnecessary background pictures, we can reduce a large number of red overdraft areas and increase the proportion of blue areas. This measure can significantly improve the program performance.

Note: For more information about the rendering mechanism, please move? /introduction-of-webp.html

Six, power optimization:

There are some measures that can significantly reduce power consumption:

To minimize the number and duration of waking up the screen, use WakeLock to deal with the wake-up problem, correctly perform the wake-up operation, and close the operation in time according to the settings to enter the sleep state.

Some operations that don't need to be performed immediately, such as uploading songs and processing pictures, can only be performed when the device is charged or the battery is fully charged.

The operation that triggers the network request will keep the wireless signal for a period of time at a time. We can package scattered network requests into one operation to avoid power consumption caused by too many wireless signals.

For the power consumption of wireless signals caused by network requests, you can also refer to work-access.html here.

Question: Suppose you have a large number of social applications installed in your mobile phone. Even if your mobile phone is in standby state, it will often be awakened by these applications to check and synchronize new data information.

Android will continue to turn off all kinds of hardware to extend the standby time of mobile phones. First, the screen will gradually dim until it is closed, and then the CPU will go to sleep. All these operations are aimed at saving valuable power resources. But even in this sleep state, most people will still work hard and wake up their mobile phones.

One of the easiest ways to wake up a mobile phone is to use the API of PowerManager. Wake-up lock keeps CPU working to prevent the screen from darkening and closing. This allows the phone to wake up, perform work, and then go back to sleep. Knowing how to get WakeLock is simple, but it is also important to release WakeLock in time.

Improper use of wake-up locks can lead to serious errors. For example, the data return time required by the network is uncertain, which causes things that originally only need 10 to wait for 1 hour, which will waste power. This is why it is very important to use the wakelock.acquice () method with timeout parameters.

But just setting a timeout is not enough to solve the problem, such as how long is the timeout ratio? When to try again and so on?

Solved: The correct way to solve the above problem may be to use an inaccurate timer. Usually, we will set a time for an operation, but it may be better to modify this time dynamically.

For example, there is another program that needs to be awakened 5 minutes later than the time you set. It is best to wait until then, when the two tasks are tied together and carried out at the same time. This is the core working principle of imprecise timer. We can customize the scheduled task, but if the system detects a better time, it can postpone your task to save power.

*? Can you refer to more knowledge about JobScheduler? http://Hu kai . me/Android-training-course-in-Chinese/background-jobs/scheduling/index . html

Seven, code specification

1) Don't declare temporary variables in forloop, and don't write try catch in it unless you have to.

2) Understand the garbage collection mechanism and avoid frequent GC, memory leakage and OOM (specifically when there is an opportunity).

3) Rational use of data types, StringBuilder instead of String, less enumeration of enum and less parent class declaration (List, Map).

4) If there are frequent new threads, it is best to execute them through thread pool to reduce the overhead of thread creation.

5) You should know the benefits of singleton and use it correctly.

6) Use more constants and less explicit "action_key" to maintain a constant class. Do not declare these constants repeatedly.

7) If you can, at least understand the strategy mode, combination mode, decorator mode, factory mode and observer mode in the design mode, which can help you understand the coupling. Even if the demand changes frequently, don't be afraid to take the lead and move the whole body. The change of requirements is not terrible, what is terrible is that there is no reasonable design before writing code.

8) Set the cache properties in the 8) view. SetDrawingCache is true.

9) Cursor? The use of. But pay attention to manage the cursor, and don't switch it every time, because switching is time-consuming. Cursor.require is used to brush the cursor.

10) Use SurfaceView to refresh the UI in the child thread. Avoid processing and drawing gestures in the same UI thread (normal view will do this).

1 1) adopts JNI, and puts time-consuming processing into c/c++ layer.

12) Some people who can operate with files try to operate with files. The speed of file operation is about 10 times faster than database operation.

13) lazy loading and caching mechanism. The time-consuming operation of accessing the network will start a new thread to complete it, not a UI thread.

14) If the method does not use member variables, it can be declared static, and the performance will be improved to 15% to 20%.

15) Avoid using getter/setter to access this field. You can declare this field as public and access it directly.

16) When a private inner class wants to access fields or methods of an outer class, its member variables should not be private, because setter/getter will be generated at compile time, which will affect performance. You can declare a field or method of an external class as package access.

17) Use floating-point numbers reasonably, which is twice as slow as integers.

18) For the performance optimization of ListView, the background color of ListView is the same as that of cacheColorHint, which can improve the rendering performance when sliding. GetView in ListView is the key to performance, and it should be optimized as much as possible here.

View; Should be reused in the getView method; You can't do complex logical calculations, especially database operations, in the getView method, otherwise the performance will be seriously affected when sliding.

19) creates an instance of a class without the new keyword. When you create an instance of a class with the new keyword, all constructors in the constructor chain are automatically called. But if an object implements the Cloneable interface, we can call its clone () method.

The clone () method does not call any class constructor. When using the design pattern, it is very simple to create a new object instance by using the clone () method if the factory pattern is used to create the object. For example, the following is a typical implementation of the factory pattern:

20) public static credit getNewCredit() {

Return new credit ();

}

The improved code uses the clone () method, as follows:

Private static credit basic credit = new credit ();

Public static credit getNewCredit() {

return(Credit)base Credit . clone();

}

The above ideas are also useful for array processing.

2 1) multiplication and division

Consider the following code:

for(val = 0; val & lt 100000; val+= 5){ alterX = val * 8; my result = val * 2; }

Using shift operation instead of multiplication operation can greatly improve performance. Here is the modified code:

for(val = 0; val & lt 100000; val+= 5){ alterX = val & lt; & lt3; myResult = val & lt& lt 1; }

22) The number of pages cached by ViewPage at the same time should be at least 3. If there are too many pagers, many pagers will be initialized when Viewpager is first displayed, so the cumulative rendering time of pager will increase and it looks very stuck.

23) When displaying, each pager should only load the network or database (UserVisibleHint=true), and it is best not to preload data to avoid waste.

24) Improve the download speed: it is faster to control the maximum number of simultaneous download tasks, and at the same time encapsulate another layer of buffer stream (such as buffered InputStream) for the input stream.

25) Providing loading speed: The best solution is to let the server provide pictures with different resolutions. There are also reasonable use of memory cache and open source framework.

Introduction: On the Optimization of Android Performance