Android Development Performance Optimization Summary (i)

Source: Internet
Author: User
Tags java reference

Android Development application first of all to pay attention to a good user experience, if a software lag serious, not smooth, often crashes, then will give users a very bad experience, thereby losing users.
  
In the actual development and learning, I summed up on the Android performance optimization, for everyone to refer to the exchange.
  
Application performance problems are manifested in many aspects, such as slow first boot, or slow access to an interface, the animation execution process is not smooth, or the animation execution lag time, the ListView list slippage process, not smooth; a specific interface that is customized by the application is slow to execute , response to a user event for a long time unresponsive (ANR), the operation of the database, the execution of a large number of data additions and deletions to the operation, slow execution, file read and write frequently, cache files too large causes the lag; After a long run, there is a random phenomenon.
  
The above problem may be more than one cause, and in many cases it is not the problem of the application itself, there may be other levels of the system problems, but reflected in the application layer. So the first thing developers need to do when dealing with performance problems is to determine whether the application itself is causing the performance problem, and then the appropriate remedy, but sometimes the logic of the application itself is normal, but due to the lack of hardware configuration of the system caused by the exception, it is necessary according to product or project needs, Take some more precise ways to optimize performance to compensate for the lack of hardware configuration.
  
Here are some ways to summarize application performance optimizations from several different perspectives.
  
First, the idea of programming
  
Performance optimizations for application tiers can often be considered in the following ways:
  
1. Understand the compiling principle of programming language, and use high-efficient coding method to improve program performance from syntax;
  
2. The use of reasonable data structures and algorithms to improve program performance, which is often the key to determine the performance of the program;
  
3. Focus on the optimization of the interface layout;
  
4. Adopt multi-thread, cache data, delay load, advance load and other means to solve serious performance bottleneck;
  
5. Reasonable allocation of virtual machine heap memory usage limit and usage rate, reduce garbage collection frequency;
  
6. Reasonable use of native code;
  
7. Reasonably Configure the database cache type and optimize the SQL statement to speed up the read speed, using transactions to speed up the write speed;
  
7. Use tools to analyze performance problems and identify performance bottlenecks;
  
There are certainly a number of other performance optimization methods, and here are just a few of the methods that are often used.
  
Second, programming skills
  
(i) Performance Tips (for Java)
  
Google official online has some tips on the application performance improvement, before the company also has a lot of summary mentioned, in this simple list, detailed content can be obtained from the official website.
  
Http://developer.android.com/training/articles/perf-tips.html
  
It is important to note that the optimization techniques listed in the article are mainly some minor performance improvements, and that determining the overall performance of the program still depends on the business logic design of the program, the data structure of the code, and the algorithm. Developers need to apply these optimization techniques to the usual coding process, adding up, and will have a great impact on performance.
  
Writing efficient code requires following two principles:
  
Do not perform unnecessary operations;
  
Do not allocate unnecessary memory;
  
Two principles, respectively, for CPU and memory, to complete the necessary operations under the premise of saving CPU and memory resources, natural execution efficiency is high. Simple to say that sounds very empty, after all, there is no unified standard to judge what is necessary and unnecessary, need to combine the specific circumstances of the specific analysis.
  
1. Avoid creating unnecessary objects
  
Creating too many objects can cause poor performance, which everyone knows, but why? It takes time to allocate the memory itself first, and then the heap memory usage is capped when the VM runs, and garbage collection is triggered when the usage reaches a certain level, and garbage collection causes the thread or even the entire process to pause. It is conceivable that if objects are created and destroyed frequently, or memory usage is high, the application will be severely stuck.
  
2. Rational use of static members
  
There are three main points to be mastered:
  
If a method does not need to manipulate dynamic variables and methods at run time, you can set the method to static.
  
The constant field is declared as "static final" because such constants are directly accessed by the static field initializer of the Dex file, otherwise it needs to be initialized at run time by some functions that are automatically generated at compile time. This rule is valid only for base types and string types.
  
Do not declare the view control as static, because the View object references the Activity object, and the object itself cannot be destroyed when the activity exits, causing a memory overflow.
  
3. Avoid internal getters/setters
  
In object-oriented design, field access using Getters/setters is often a good rule, but limited to hardware conditions in Android development, unless the field needs to be publicly accessed, it is not recommended to use a limited range of internal access (for example, in-package access) getters/ Setters. When JIT is turned on, direct access is 7 times times faster than indirect access.
  
4. Using the enhanced for loop
  
Priority use of the enhanced for loop usually gets more efficient, except in the case where ArrayList is traversed with a normal for loop efficiency.
  
5. Use public instead of private to enable private internal classes to access external class members efficiently
  
The private inner class's methods access the private member variables and methods of the external class, are syntactically correct, but the virtual machine is not directly accessible at run time, but at compile time, some of the package-level static methods are automatically generated in the external class, and the internal classes invoke these static methods to access the private members of the external class when executed. In this way, there is a layer of method calls, performance loss.
  
One way to solve this problem is to change the private member of the external class to the package level, so that the inner class can be accessed directly and, of course, if it is designed to be acceptable.
  
6. Proper use of floating-point types
  
Floating-point types in Android devices are probably twice times slower than integer data processing, so don't use floating-point types if the integer type solves the problem.
  
In addition, some processors have hardware multiplication but no division, in which case the division and modulo operations are implemented by software. To improve efficiency, you might consider rewriting some division operations directly into multiplication implementations when writing expressions, such as "X/2" to "X * 0.5".
  
7. Use <merge> to optimize the layout layer number. Use <include> to share layouts.
  
8. Delay loading view. Using viewstub avoids some infrequently used views that are referenced for long periods of time, taking up memory.
  
9. Remove activity default background to increase activity loading speed.
  
If you are sure to use an opaque background in your activity, you can remove the activity's default background.
  
In the Code: GetWindow (). setbackgrounddrawable (NULL);
  
You can also set it in the styles file and configure it in the manifest file.
  
<style name= "MyStyle" parent= "Apptheme" >
  
<item name= "Android:windownotitle" >true</item>
  
<item name= "Android:windowbackground" > @null </item>
  
</style>
  
The use of 10.cursor.
  
Be careful to manage the cursor, not every time you turn the cursor off. It is very time-consuming to turn the cursor off.
  
The cursor that is no longer used should be remembered as closed (typically in the finally statement block).
  
In one case, we can't just close the cursor, which is the case in CursorAdapter, but notice that CursorAdapter does not automatically close the cursor at the end of the acivity, so You need to close it manually in the OnDestroy function.
  
protected void OnDestroy () {
  
if (madapter! = null && MADAPTER.GETCUROSR (www.furggw.com)! = null) {
  
Madapter.getcursor (). Close ();
  
}
  
Super.ondestroy ();
  
11. When broadcasting broadcast dynamic registration, remember to unregisterreceiver at the end of the caller's life cycle to prevent memory leaks.
  
12. Performance optimizations for the ListView
  
Item minimizes the level of controls and layouts used, the background color sets the same color as the Cachecolorhint, and the layout of item in the ListView is critical, and you must minimize the layout of the controls you use. Relativelayout is an absolute tool through which you can reduce the level of layout. Reuse the control as much as possible, which reduces the memory usage of the ListView and reduces the number of GC times when sliding. The background color of the ListView is set to the same color as the cachecolorhint, which improves rendering performance when sliding. The GetView in the ListView is the key to performance, which should be optimized as much as possible. In the GetView method, it is not possible to do complicated logical computation in the View;getview method, especially the database operation, otherwise it will seriously affect the performance of sliding; When the ListView data item is large, the paging load is considered.
  
13. Note the use of the thread synchronization mechanism (synchronized) to prevent multiple threads from accessing an object at the same time when an exception occurs.
  
14. Reasonable use of stringbuffer,stringbuilder,string
  
In a simple string concatenation, the efficiency of string is the highest, for example string s = "Hello" + "world";
  
But it is important to note that if your string is from another string object, the speed is not so fast, for example:
  
String str2 = "This is";
  
String STR3 = "a";
  
String STR4 = "Test";
  
String str1 = str2 +str3 + str4;
  
StringBuilder is required here.
  
In a single thread, StringBuilder performance is higher than StringBuffer. Multithreading is required to use StringBuffer for thread safety because it is synchronous. Generally used under the general StringBuilder.
  
15. Use local variables as much as possible
  
The parameters passed when the method is called and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables, instance variables, and so on, are created in the heap and are slower. Also, depending on the compiler/JVM, local variables may be further optimized.
  
16.I/O stream operation Remember to close the stream object in time.
  
17. Use Intentservice instead of service
  
Intentservice and service are a service, the difference is that Intentservice uses a queue to join the requested intent to the queue, and then open a worker thread (thread) To handle the intent in the queue (in the Onhandleintent method), for asynchronous StartService requests, Intentservice handles the completion of one and then processes the second, and each request is in a separate worker Thread, it does not block the main thread of the application, and it is better to use Intentservice to handle time-consuming operations if there is a time-consuming operation than opening a new thread within the service.
  
18. Use Application context instead of context in activity
  
Do not allow objects with long life cycles to refer to the activity context, that is, to ensure that the object referencing the activity is the same as the activity itself life cycle
  
For objects with long life cycles, you can use the application Context
  
Do not set the context object to static.
  
19. Objects in the collection should be cleaned up in time
  
We usually add references to some objects to the collection, and when we don't need the object, we don't clean up its references from the collection, so the collection gets bigger. If the set is static, the situation is even worse.
  
Use of 20.Bitmap
  
The larger bitmap attention compresses and then uses, the load high definition large picture may consider the Bitmapregiondecoder use,
  
No longer use the bitmap note in time Recycle (www.272345.cn).
  
21. Clever use of soft references (softrefrence)
  
Sometimes we don't keep a reference to it after we use bitmap, so we can't call the Recycle function. By using soft references skillfully, the bitmap can be effectively released when the memory is not fast enough. An introduction to the Java reference mechanism can be seen in one of my other blogs: http://blog.csdn.net/gs12software/article/details/51051813
  
22. Try not to use a large image of the whole as a resource file, use 9path images as much as possible
  
The application icon takes precedence in the Mipmap directory (Androidstudio Environment), other Resource Graph,. 9 figure should be placed under drawable-xxxx, need to be copied to the phone on the SD card should be placed in the asset directory
  
23. Understand and use library functions
  
The Java standard Library and the Android framework contain a large number of efficient and robust library functions, many of which are implemented in native, and are often much more efficient than the code we use to implement the same functionality in Java. So good at using system library functions can save development time, and it is not easy to make mistakes.
  
24. About WebView
  
Remember to destroy the webview when the activity or fragment destroys it.
  
@Override
  
protected void OnDestroy () {
  
if (webview!= null) {
  
Webview.destroy (www.huachenj157.com);
  
webview= null;
  
}
  
Super.ondestroy (www.furongpt.com);
  
Iii. using tools to analyze application performance
  
(This section is more, see the "Android Development Performance Optimization Summary (ii)" for details.

Android Development Performance Optimization Summary (i)

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.