Introduction to Android performance optimization and android Performance Optimization

Source: Internet
Author: User
Tags webp

Introduction to Android performance optimization and android Performance Optimization

I. Summary:

    This article describes Android Performance Optimization in terms of rendering mechanism, UI optimization, multi-thread processing, cache processing, power optimization, and code specifications.

 

Ii. Rendering Mechanism Optimization:

The main cause of performance problems, such as choppy, that most users perceive, is the rendering performance.

The Android system sends a VSYNC signal every 16 ms to trigger rendering of the UI. If each rendering is successful, the 60 FPS required for smooth images can be achieved. In order to achieve 60 FPS, this means that most operations of the program must be completed within 16 Ms.

    

If one of your operations takes 24 ms, the system will not be able to perform normal rendering when the VSYNC signal is obtained. This will cause Frame loss. The user will see the same frame within 32 Ms.

    

Probably: it may be because your layout is too complex to complete rendering within 16 Ms. It may be because there are too many painting units stacked on your UI, it may also be because the number of animation executions is too large. These will cause excessive CPU or GPU load.

Resolved: You can use some tools to locate the problem. For example, you can use HierarchyViewer to check whether the layout in the Activity is too complex. You can also use the developer options in the mobile phone settings, open Show GPU Overdraw and other options for observation.

You can also use TraceView to observe the CPU execution and quickly locate performance bottlenecks.

    

Overdraw ):

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

      

Tips: You can set the developer options in the cell phone to enable the Show GPU Overdraw option to observe the Overdraw situation on the UI.

      

Illustration: blue, light green, light red, dark red represents four different levels of Overdraw, our goal is to minimize the red Overdraw to see more blue areas.

Tips: Overdraw is sometimes caused by a large number of overlapping parts in your UI layout, and sometimes because of non-necessary overlapping backgrounds. For example, an Activity has a background, Layout has its own background, and the Child View has its own background.

Only remove unnecessary background images, which can reduce the red Overdraw area and increase the proportion of the blue area. This measure can significantly improve program performance.

 

Note: To get more about rendering, move to the https://www.oschina.net/news/60157/android-performance-patterns

 

3. UI optimization:

1) First, let's talk about the process of drawing a view: measure-layout-draw.

Ps: a specific process for online search + _ +

2) The more child controls, the longer the Painting time.

For a multi-item component such as Listview or GridView, reusing items can reduce the number of inflate times and achieve reuse through the ViewHolder method of setTag and getTag. Note that, the control in holder should be reset before value assignment to avoid image and text disorder.

* The following is a simple example: (use annotations whenever possible. Open-source frameworks with many annotations can be used: butterKnife, AndroidAnnotation, and Dragger2)

 1 static class ViewHolder{ 2     @InjectView(R.id.imageView1) 3     ImageView imageView1; 4     @InjectView (R.id.text1) 5     TextView textView1; 6 } 7  8 @Override 9 public View getView(int position, View convertView, ViewGroup parent) {10     ViewHolder holder;11              12     if(convertView == null){13        holder = new ViewHolder();14        convertView = LayoutInflater.from(mContext).inflate(R.layout.listview_item, null);15        convertView.setTag(holder);16      }else{17          holder = (ViewHolder)convertView.getTag();18      }19              20          holder.imageView1.setImageResource(R.drawable.ic_launcher);21          holder.textView1.setText(mData.get(position));  22              23          return convertView;24 }

3) UI ReView (view check)

1. Reducing the view level can effectively reduce memory consumption, because the view is a tree structure and will be traversed every time you refresh and render it.

2. To reduce the view level, you first need to know the view level. Therefore, the following describes a very useful tool hierarchyviewer In the SDK. You can find it at the following address: your sdk path \ sdk \ tools

      

3. as you can see, hierarchyviewer can clearly view the hierarchy of the current view, and view the execution efficiency of the view (small dots on the view, Green indicates smoothness, followed by yellow and red ), therefore, we can easily check which views may affect our performance and further optimize it.

Hierarchyviewer also provides a two-way display method that allows you to view detailed screen images. You can find problems at the pixel level.

4) use of some labels

<Merge>: It plays an important role in optimizing the UI structure. The objective is to optimize the entire Android Layout structure and the Layout layers by deleting redundant or additional layers.

<Include>: You can use this label to directly load external xml into the current structure. It is a common tag for reusing UI resources to share the layout.

<ViewStub>: dynamically loads a view. This label allows the UI to visually display the View invisible under special circumstances, however, the greater significance is that the Views wrapped by this label do not occupy any memory space by default.

 

4. multi-thread processing:

1. Multiple multi-threaded tools (AsyncTask, HandlerThread, IntentService, ThreadPool) provided by Android, many operations must be executed by the main thread (UI thread), such:

      

2. The screen refresh frequency of Android system is 60 fps, that is, every 16 MS refresh once. If in a painting process, our operation can not be completed within 16 MS, then it can not catch up with the drawing of the bus, can only wait for the next round.

This phenomenon is called "Drop frame". What users see is that the interface is not continuous and choppy.

      

3. HandlerThread is a combination of MessageQueue, logoff, and Handler. When an application starts, the system creates a process and main thread for the application. The main thread here is a HandlerThread.

      

4. Notes:

1) multi-thread concurrent resource access should follow the important principle thatAtomicity, visibility, and orderliness. When there is no synchronization mechanism, multiple threads read/write memory simultaneously may cause unexpected problems:

① Thread security problems; ② the life cycle of the UI component is not fixed; ③ Memory leakage caused by thread reference

2) Do not reference the UI component or Activity in any sub-thread.

3) keep the response intact. ANR:

① Remove time-consuming operations from the UI thread. This method also prevents the system from responding (ANR) dialog box during user operations. What needs to be done is inherit AsyncTask to create a background working thread and implement the doInBackground () method.

② Another way is to create a Thread class or HandlerThread class by yourself and specify the Thread priority.

4) use StrictMode to check the potential time-consuming operations in the UI thread, and use some special tools such as Safe. ijiami, Systrace, or Traceview to find the bottleneck in your application. Use a progress bar to show you the operation progress.

 

5. cache processing:

The following describes several aspects of Cache Optimization:

    Cache Mechanism:Network + database. To avoid getting duplicate data from the network, you can set a maximum request interval in activity, fragment, or each component.

For example, when a listview requests data for the first time, it saves a copy to the database and writes down the timestamp. When it is re-initialized next time, it determines whether the maximum time interval (such as 5 minutes) is exceeded ), if no, only the database data is loaded, and no network request is required.

(Of course, some implicit http request frameworks will cache server data and no longer request the network for a certain period of time, or directly return the previously cached data when the server returns 304)

 

 

Network: 1) In json format, WebP replaces jpg and supports resumable data transfer. Multiple requests are merged into one with no redirection, server cache and Server Load balancer.

2) for the client itself, in addition to the above implementation, we also need to properly cache, control the maximum number of concurrent requests, promptly cancel invalid requests, filter duplicate requests, and set the timeout time, request priority settings.

* WebP: the advantage of WebP is that it has a better image data compression algorithm, which can bring a smaller image size and has the ability to identify non-differential image quality with the naked eye;

At the same time, it has lossless and lossy compression modes, Alpha transparency, and animation features, and the conversion effects on JPEG and PNG are excellent, stable, and unified.

The converted WebP supports Alpha transparency and 24-bit color numbers. The PNG8 color is not rich enough and may cause edges in the browser.

* For more information, see: http://isux.tencent.com/introduction-of-webp.html

 

 

6. Power Optimization:

The following measures can significantly reduce power consumption:

      • We should minimize the number and duration of screen wakeup. We should use WakeLock to handle the wake-up problem, correctly perform the wake-up operation, and close the operation in time to enter the sleep state.

      • Some operations that do not have to be performed immediately, such as uploading songs and image processing, can be performed only when the device is in the charging status or when the power is sufficient.

      • The operation that triggers network requests keeps wireless signals for a period of time. We can package scattered network requests for one operation to avoid excessive power consumption caused by wireless signals.

For network requests caused by wireless signal power consumption, you can also refer to here http://hukai.me/android-training-course-in-chinese/connectivity/efficient-downloads/efficient-network-access.html

    

 

Ask: assume that your mobile phone has a large number of social apps installed. Even if your mobile phone is in the standby status, these apps will often wake up to check and synchronize new data information.

Android will keep disabling hardware to prolong the phone's standby time. First, the screen will gradually become dark until it is disabled, and then the CPU enters sleep. All these operations are aimed at saving valuable power resources. But even in this sleep state, most applications will still try to work, and they will constantly wake up their mobile phones.

One of the simplest ways to wake up a mobile phone is to use the PowerManager. WakeLock API to keep the CPU working and prevent the screen from being dimmed. This allows the phone to be awakened, executed, and then sleep. It is easy to know how to obtain WakeLock, but it is also very important to release it in time.

Improper use of WakeLock may cause serious errors. For example, if the returned Time of the network request data is unknown, it takes only 10 seconds to wait for one hour, which will waste the power consumption. This is also why the wakelock. acquice () method with the timeout parameter is critical.

However, setting a timeout setting is not enough to solve the problem. For example, how long is the timeout setting more appropriate? When can I retry?

 

Resolved: To solve the problem above, the correct method may be to use an inaccurate timer. Generally, we will set a time for an operation, but it may be better to modify it dynamically.

For example, if another program needs to wake up five minutes later than the time you set, it is best to wait until that time, when the two tasks are bundled together, this is the core working principle of the non-precise timer. We can customize the scheduled task, but if the system detects a better time, it can delay your task to save power consumption.

    

* For more information about JobScheduler, refer to the http://hukai.me/android-training-course-in-chinese/background-jobs/scheduling/index.html.

 

VII. Code specifications

  

1) do not declare temporary variables in the for loop. Do not write try catch in the for loop.

2) understand the garbage collection mechanism to avoid frequent GC and memory leaks, and OOM (a special opportunity)

3) reasonably use the data type. Use StringBuilder to replace String, use less enum, and use less parent class declaration (List, Map)

4) if you have frequent new threads, execute them through the thread pool to reduce thread creation overhead.

5) You need to know the benefits of a singleton and use it correctly.

6) use multiple constants, use less explicit "action_key", and maintain a constant class. Do not declare these constants again.

7) If you can, at least understand the policy patterns, combination patterns, decoration patterns, factory patterns, and observer patterns in the design pattern, which can help you properly decouple, even if demand changes frequently, you don't have to worry about getting started. The requirement change is not terrible. What is terrible is that there is no reasonable design before writing the code.

8) set the cache attribute in View. setDrawingCache to true.

9) Use of cursor. However, you must manage cursor. Do not close cursor every time you open it, because it takes a lot of time to close Cursor. Cursor. require is used to brush cursor.

10) Use SurfaceView to refresh the UI in the sub-thread to avoid processing and drawing gestures in the same UI thread (common views do this)

11) Use JNI to put time-consuming processing on the c/c ++ layer for processing.

12) for some operations that can be performed on files, try to use file operations. File Operations are about 10 times faster than database operations.

13) lazy loading and caching mechanisms. Start a new thread for time-consuming operations to access the network, instead of using the UI thread.

14) if the method does not use member variables, you can declare the method as static, and the performance will increase to 15% to 20%.

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

16) when a private internal class needs to access the field or method of an external class, its member variables should not be private, because setter/getter will be generated during compilation, affecting the performance. You can declare the field or method of the external class as the package access permission.

17) make proper use of floating point numbers. Floating Point Numbers are twice slower than integer ones.

18) for ListView performance optimization, the background color of ListView is the same as that of cacheColorHint, which can improve the rendering performance during sliding. In ListView, getView is the key to performance. We should optimize it as much as possible.

View must be reused in the getView method. Complex logical computing, especially database operations, cannot be performed in the getView method. Otherwise, the sliding performance will be seriously affected.

19) when the new keyword is used to create an instance of the class without 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 Design Pattern, it is very easy to use the clone () method to create a new object instance if you create an object in Factory mode. For example, the following is a typical Implementation of the Factory mode:

20) public static Credit getNewCredit (){
Return new Credit ();
}
The improved code uses the clone () method as follows:
Private static Credit BaseCredit = new Credit ();
Public static Credit getNewCredit (){
Return (Credit) BaseCredit. clone ();
}
The above idea is also useful for Array Processing.

21) multiplication and division

      Consider the following code:

22) it is best to set the number of pages cached by ViewPager to a minimum value of 3 at the same time. If there are too many pages, there will be a lot of pager initialized by ViewPager when it is displayed for the first time, so that the accumulated rendering time of pager will increase, it looks like a card.

23) Each pager should load the network or database only when it is displayed (UserVisibleHint = true). It is best not to pre-load the data to avoid waste.

24) Improved download speed: It is necessary to control the maximum number of tasks to be downloaded at the same time, and adding a buffer stream to InputStream will be faster (such as BufferedInputStream)

25) provide loading speed: it is the best solution for the server to provide images of different resolutions. There is also a rational use of the memory cache, the use of open-source frameworks

 

    

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.