Summary of performance optimization during android app development, androidapp

Source: Internet
Author: User

Summary of performance optimization during android app development, androidapp

The performance of a mobile app needs to be optimized from the development process so that the user experience can be improved. If we open an app and it is not smooth, this will affect users' attitudes towards the application. Product dogs pay attention to these human-computer interaction experience.

Google has been constantly optimizing its android system. In terms of fragmented processing and system performance, ios is doing better in this regard. The configuration is lower than android, but the smoothness is higher than android, better experience.

Official recommendation: http://www.oschina.net/news/60157/android-performance-patterns

I have summarized several major aspects in development to facilitate smooth application.

The performance problems of applications are often reflected in many aspects. For example, the first time an application starts slowly, or when it enters a certain interface, it starts an animated interface, the animation execution process is not smooth, or the animation execution is slow for a long time. The ListView list slides smoothly, but the execution speed of a specific interface customized by the application is slow, for example, the sliding between the left and right sides of the Launcher application desktop is not smooth; the system does not respond to a user event for a long time (ANR); when operating the database, the system performs addition, deletion, modification, and query operations on a large amount of data, the execution speed is slow. After the application runs for a long time, the program gets stuck at random.

There may be more than one reason for the above problems, and in many cases it is not a problem of the application itself, or it may be a problem at other levels of the system, but it is only reflected in the application layer. Therefore, the application layer always bears the brunt. When developers are dealing with performance problems, the first thing they need to do is to determine whether it is a performance problem caused by the application itself, and then take the right medicine; however, in some cases, the logic of the application itself is normal, which is obviously caused by insufficient hardware configuration of the system. In this case, we need to optimize the performance in some more radical ways based on the product or project requirements, to make up for hardware configuration deficiencies.

Here are some methods to optimize the application performance from different perspectives.

I. programming ideology

The performance optimization of the application layer can be considered from the following aspects:
1. Understand the compilation principles of programming languages and use efficient coding methods to improve program performance;
2. Using reasonable data structures and algorithms to improve program performance is often the key to determining program performance;
3. Optimize the UI layout;
4. Multiple Threads, cached data, delayed loading, and early loading are used to solve serious performance bottlenecks;
5. Reasonably configure the VM heap memory usage limit and usage to reduce the garbage collection frequency;
6. use native code properly;
7. Reasonably configure the database cache type and optimize SQL statements to speed up reading, and use transactions to speed up writing;
7. Use tools to analyze performance issues and identify performance bottlenecks;
Of course, there must be many other performance optimization methods. Here we only list some frequently used methods.

Ii. Programming Skills
(1) Performance Tips (For Java)
There are some tips on improving the performance of applications on the Google official website, which has been mentioned in many summaries in the company before. Here, we will give a brief list of details available on the official website.
Http://developer.android.com/training/articles/perf-tips.html
It should be noted that the optimization techniques listed in this article mainly involve minor performance improvements. The overall performance of the program depends on the business logic design of the program, the data structure and algorithm of the Code. R & D personnel need to apply these optimization techniques to the normal coding process, which will greatly affect the performance.
Writing efficient code requires two principles:
No unnecessary operations;
Unnecessary memory allocation;
The two principles are aimed at CPU and memory respectively. When necessary operations are completed, the CPU and memory resources are saved as much as possible, and the natural execution efficiency is high. Simply speaking, it sounds very imaginary. After all, there is no unified standard to judge what is necessary and unnecessary. It is necessary to analyze it according to the specific situation.
1. Avoid creating unnecessary objects
Creating too many objects will result in poor performance. Everyone knows, but why? First, it takes time to allocate the memory itself. Secondly, there is an upper limit on the heap memory usage when the VM runs. When the usage reaches a certain level, garbage collection is triggered, garbage collection causes the thread or even the entire process to pause. It can be imagined that if an object is frequently created and destroyed, or the memory usage is very high, the application will be severely choppy.
2. reasonably use static members
There are three main points to learn:
If a method does not need to operate dynamic variables and methods at runtime, you can set the method to static.
The constant field must be declared as "static final", because the constant will be directly accessed in the static field initializer of the dex file, otherwise, some functions automatically generated during compilation must be used for initialization during runtime. This rule is only valid for the basic and String types.
Do not declare the View control as static because the View object references the Activity object. When the Activity exits, the object itself cannot be destroyed, resulting in memory overflow.
3. Avoid internal Getters/Setters
In object-oriented design, using Getters/Setters for field access is usually a good principle, but in Android development, it is limited to hardware conditions unless the field needs to be publicly accessed, otherwise, Getters/Setters is not recommended for internal access within a limited range (for example, intra-package access. When JIT is enabled, direct access is 7 times faster than indirect access.
4. Use the for-each loop
The use of the for-each loop is preferred, which usually achieves higher efficiency. In addition, the use of manual counting cycles for the ArrayList is more efficient.
5. Use package instead of private to allow private internal classes to efficiently access external class members
The method of the private internal class accesses the private member variables and methods of the external class. It is correct in syntax, but the virtual machine does not directly access the variables and methods at runtime, instead, some static package-level methods are automatically generated in the external class during compilation. During execution, the internal class calls these static methods to access the private members of the external class. In this way, there is an additional layer of method calling, and the performance is compromised.
One way to solve this problem is to change the private members of the external class to the package level, so that the internal class can be accessed directly. Of course, the premise is that the design is acceptable.
6. Avoid floating point type
In terms of experience, the floating point type in Android devices is about twice slower than the integer data processing speed, so if the integer type can solve the problem, do not use the floating point type.
In addition, some processors have hardware multiplication but no division. In this case, division and modulo operations are implemented by software. To improve efficiency, some Division operations can be rewritten as multiplication operations when writing computation formulas, for example, "x/2" to "x * 0.5 ".
7. understand and use library functions
The Java standard library and Android Framework contain a large number of efficient and robust library functions. Many functions are also implemented using native, generally, this is much more efficient than code that uses Java to implement the same function. Therefore, the use of system library functions can save development time and is not prone to errors.
(2) Layout Performance Optimization
The layout directly affects the display time of the interface. There is no technical difficulty in optimizing the performance of the interface layout. I personally think that the most important thing is whether to recognize the importance of layout optimization. At first, I also thought that layout itself would not be a performance bottleneck, and it would be difficult to optimize it. It was hard to write complicated layout files, or the native code was like that, I also used log to view the setContentView time. It seems that there is no problem. I really don't want to study it. But in fact, the layout problem is not as simple as imagined.
The performance optimization of the layout is important because of the following two aspects:
· The layout file is an xml file. The inflate layout file parses the xml file and creates and associates the corresponding layout Objects Based on the tag information. The more labels and attribute settings in xml, the deeper the node tree, the more judgment logic to be executed during parsing, the more nested and recursive functions of functions, and the more time consumption;
· The inflate operation is only the first step of the layout impact. An interface should be displayed, and a series of measure, layout, and draw operations should be executed after requestLayout, the execution time of each step is affected by the layout. The final display of the interface is implemented only after all these operations are completed. Therefore, if the layout quality is poor, the time cost for each operation will be increased, and the final display time will be relatively long.
So how to optimize the layout? Summary:
1. Follow one rule: the layout levels should be as few as possible
That is to say, to achieve the same layout effect, the depth of the tree in the xml file should be as deep as possible. To do this, you need to use the layout control properly:
Typically, you can use RelativeLayout instead of LinearLayout to achieve the same layout effect;
Another is that if node A of the layout tree has only one sub-node B and Node B has only one sub-node C, then Node B can usually be removed;
Use the <merge> label reasonably. If layout X can be included in Y, consider whether the root node of X can be set to <merge>, in this way, the child nodes of <merge> are added to Y during parsing, but <merge> is not added.
2. Use Lint to analyze the Layout
Lint is a tool under the tools directory in the SDK. ADT integrates the visual control interface of Lint. Using Lint to scan an application, it analyzes the application from many aspects and prompts where there may be defects, including performance-related content. You can learn more on the Google website.
Http://developer.android.com/tools/debugging/improving-w-lint.html
Http://developer.android.com/tools/help/lint.html
3. Use HierarchyViewer to analyze the Layout
HierarchyViewer (HV) is also a tool under the tools directory in the SDK. The ADT also integrates the visual control interface of HV. You can use HV to view the layout of the current interface, which provides a lot of information, two of which can help us analyze performance problems:
· The Tree View of HV shows the relationship between View Controls and can be used to check whether there are any situations mentioned in.
· In the Tree View, the time for each node's measure, layout, and draw can be displayed, and each item uses a dot to indicate whether the time consumption is normal, each dot uses green, yellow, and red to indicate time-consuming, warning, and danger. This makes it easy to find performance bottlenecks. If the time is not displayed in the fruit tree view, you can click "Obtain layout times for tree rooted at selected node" to refresh the page.
Http://developer.android.com/tools/debugging/debugging-ui.html
4. Use ViewStub to delay loading the view
ViewStub is a lightweight view that has no size and does not nest or render anything in the layout. If some view controls do not need to be displayed immediately, you can write them to a separate layout file and use the ViewStub label instead, you can use ViewStub to load the view to display the content.
Http://developer.android.com/training/improving-layouts/loading-ondemand.html
Iii. Use of tools
Good coding habits can make program execution more efficient, but various performance problems still occur during actual operation. Fortunately, there are many powerful tools that can help us analyze performance bottlenecks and locate problems. The tools described below must already be familiar to you. Many articles on the Internet are well written. I will not repeat them here. I will only describe the key points of these tools in use. For detailed usage of these tools, please refer to an article on the Internet: http://blog.csdn.net/innost/article/details/9008691.
(1) Traceview
The most direct way to optimize performance is to repeat existing performance problems and monitor the execution process of the program in this process, if you can easily analyze the call relationship and execution time of functions in the program, you can easily find the performance bottleneck.
Traceview is a tool used to analyze the function call process. It can be used to analyze performance problems conveniently. It takes the following steps:
Use the Android Debug API or DDMS to monitor the program running process;
To repeat existing performance problems, use step 1 to obtain the function call log file, that is, the trace file, during the program process;
Use Traceview to import the trace file;
The Traceview interface is intuitive, but you need to pay special attention to the following points during the analysis:
1. Meanings of columns in Profile Panel:
· Incl-indicates the execution time of the function itself and other nested functions;
· Excl-refers to the execution time of functions that do not contain nested functions;
· Cpu Time-the total number of CPU Time slices used during function execution, excluding the waiting Time;
· Real Time-refers to the Real Time of the function execution process, including the waiting Time;
· Cpu Time/Call-indicates the average CPU Time of each function Call;
· Real Time/Call-indicates the average Real Time of each function Call;
· Cballs + Recur cballs/Total-indicates the Total number of function Calls + the percentage of recursive Calls;
· %-A column with % indicates the percentage of the function execution time to the total sampling time;
2. How to analyze performance bottlenecks
The first thing to worry about is the CPU time. You can find out the program's own problems. The actual time will be affected by other factors in the system. Then we can analyze the data from four aspects:
1) analyze the functions that have been executed for a long time at a time
You can click the "Cpu Time/Call" column to sort them in descending order and find out the functions that we are concerned about when the execution Time is relatively long, then, view the detailed execution process inside the function;
2) analyze which functions are called too many times
You can click the "CILS + recurcils/Total" column, sort them in descending order, and find out which execution times are relatively large and also the functions we are concerned about, then, view the detailed execution process inside the function;
3) analyze which functions have a long execution time
Some functions do not have a very long execution Time and the total number of calls is not very large, but the total execution Time obtained by multiplying the two is long. You can click "Incl Cpu Time ", sort these functions in descending order;
4) Sometimes we clearly need to look at some specific methods of specific classes. We can search in the bottom of the page, but it seems that only full lowercase input is supported.
3. note: The JIT function is disabled when trace information is sampled using APIs or tools. At the same time, because the sampling itself also needs to occupy system resources, therefore, using Traceview to view the function execution time is much slower than normal operation time. We only need to care about the relative time consumption.
(2) dmtracedump
In addition to TraceView analysis, trace files can also be analyzed using another tool, dmtracedump, which has powerful functions. If you think it is painful to search for classes and functions in Traceview, try this tool.
Dmtracedump is an executable file under the tools directory of the SDK. You can view its help information and execute commands similar to the following:
Dmtracedump-h-g tracemap.png path-to-your-trace-file> path-to-a-html-file.html
Then we can get two things: one is the tree map of each function call, which can view the function relationship at a glance; the other is an operable html file, open it in a browser and you can easily find the classes or functions you care about.
(3) systrace
Systrace is a powerful performance analysis tool introduced from 4.1. It relies on the ftrace function of Kernel and can analyze the performance of many important modules in the system, especially the graphic display module. It supports tracking system I/O operations, kernel work queues, CPU loads, and running status of various Android subsystems.
To use Systrace, you must first enable the tracking and monitoring mode through the API provided by Android or DDMS, then run the program to generate a log file, and finally analyze the log file. Systrace outputs an html file, which can be viewed directly in a browser. If you use the ADT of the latest version, you can easily perform operations on the interface without using commands. You can search for more details on the Internet.
Iv. Thoughts on Performance Optimization
Performance optimization is a big topic. In addition to discussing how to optimize, it is also important to determine whether optimization is required. As early as a few decades ago, there were a lot of discussions about performance optimization, and then came to a profound truth: optimization is more likely to bring harm, rather than benefits, especially immature optimization. During the optimization process, the software you generate may be neither fast nor correct, and cannot be easily corrected.
Do not sacrifice a reasonable structure for performance. Try to write good programs instead of quick ones.
However, this does not mean that you can ignore performance issues before completing the program. Implementation problems can be corrected through later optimization, but structural defects that spread globally and limit performance are almost impossible to be corrected unless you re-compile the program. After the system is completed, changing a basic aspect of your design will lead to a pathological structure of your system, making it difficult to maintain and improve. Therefore, you should consider performance issues during the design process.
 
Try to avoid design that limits performance. Consider the performance consequences of your code design. It is a very bad idea to make changes to the Code for good performance. Performance needs to be measured before and after each 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.