Neglected optimization points for Android performance optimization

Source: Internet
Author: User

For performance optimization This knowledge point, is too broad, the blogger himself has been very concerned about this aspect of learning, and for performance optimization It includes very very very many aspects, such as: I/O optimization, network operation optimization, memory optimization, data structure optimization, code hierarchy optimization, UI rendering optimization, Optimization of CPU resource utilization, optimization of exception handling, etc...

This article describes the blogger's own understanding of some of the areas that can be optimized in Android development

ArrayList and Vectors

ArrayList and vectors are internal array implementation of the list, the only difference between them is the support of multithreading, ArrayList is thread insecure, and vector internal to most methods are synchronized, is thread-safe, since it is thread-safe, So the performance is certainly not as good as ArrayList (of course, the idea is certainly right), but this needs to see what aspect, ArrayList in Add, get, remove and other operating efficiency is certainly higher than the vector, and in memory, Vector is better than ArrayList, this is the root of the ArrayList expansion strategy caused by, later analysis.

Implements a collection of randomaccess interfaces using Fori traversal

Let's talk about the traversal of the list collection in three ways: foreach, iterator, Fori.
In the development of the general need to traverse the first choice is foreach, because it is efficient, this point of view is correct, but needs to be divided into occasions.
Here's how I tested the ArrayList collection with 100w data in these three ways:

Long start = System.currenttimemillis (); for(inti =0; i < size; i++) {data.Get(i); } LongEnd= System.currenttimemillis ();Log. V ("Zxy","Fori Cost:"+(End-start)); Start = System.currenttimemillis (); for(Integer Integer:data) {        }End= System.currenttimemillis ();Log. V ("Zxy","foreach Cost:"+(End-start));        iterator<integer> Iterator = Data.iterator (); Start = System.currenttimemillis (); while(Iterator.hasnext ()) {iterator.Next(); }End= System.currenttimemillis ();Log. V ("Zxy","iterator Cost:"+(End-start));
 One- +  the: One:44.276 1418-1418/? V/zxy:fori Cost: - One- +  the: One:44.380 1418-1418/? V/zxy:foreachSpend: the One- +  the: One:44.476 1418-1418/? V/zxy:iterator Cost: the

And often what we call efficient foreach is not as good as the traversal, and fori efficiency is the best, because the ArrayList and vector sets are implemented internally by arrays, so random access is fast, for lists that can be accessed randomly, The JDK implements the Randomaccess interface for them, which means that fast random access is supported.
While traversing the LinkedList collection with 1w of data:

 One- +  the: -:23.984 1737-1737/? V/zxy:fori Cost:351 One- +  the: -:23.988 1737-1737/? V/zxy:foreachSpend:2 One- +  the: -:23.992 1737-1737/? V/zxy:iterator Cost:4

The foreach performance is the best, so the array, or the implementation of the Randomaccess interface list, traversal with fori performance best, to LinkedList and other linked list-implemented collection traversal using foreach or iterator performance best, Because the implementation of foreach is achieved through iterator.
We can judge the list traversal in this way:

        if (listinstanceof RandomAccess)        {            for0list.size(); i++) {}        else {            Iterator<?list.iterator();            while (iterator.hasNext()) {                iterator.next();            }        }
When constructing ArrayList with predictable capacity, specify the initial size as much as possible

The ArrayList internal expansion strategy is that when the number of elements it stores exceeds its existing size, It will be 1.5 times times capacity to expand, that is, if the current ArrayList capacity of 10000, then it needs to store an element, that is, the 10,001th element, because the capacity is not enough to do a single expansion, and ArrayList capacity after the expansion has become 15000, and more than one element more than 50 00 Elements of space, which is too wasteful of memory resources, and the expansion will also cause the entire array of memory replication, and the ArrayList collection default size is 10, so reasonable settings ArrayList capacity to avoid the expansion of the collection. ArrayList internal expansion and array replication code are:

            ObjectnewObject[s +                    2) ?                     1)];            00, s);            array = a = newArray;

and the vector internal expansion strategy for on-demand capacity, each time + 1:

        if0) {            if ((adding = elementData.length0) {                1;            }        else {            adding = capacityIncrement;        }        E[] newData = newElementArray(elementData.length + adding);

Similarly, there are respective scaling strategies in many map collections, such as HashMap each time the capacity is equal to the original capacity. In the StringBuffer and StringBuilder that we used to do string stitching, we actually have the capacity expansion strategy, which defaults to 1.5 times times the original size.

So, in these APIs that need to be expanded, if you know the size of the data beforehand, it is pre-set, which not only avoids the wasted space caused by the expansion, but also avoids the large amount of data copying from internal calls to System.arraycopy ().

If the program needs to make random access to the list by index subscript, priority should be given to ArrayList and vectors, as far as possible not to use LinkedList

Although ArrayList is less than a vector in memory, it is highly efficient for data manipulation, especially on mobile devices such as Android, where it is advisable to take a bit of space-time-swapping, but with regard to thread safety, vector is used.

If a method does not need to use the member of the object, then the method is set to static

A static call to this method is faster than an object calling the method, because it is possible to see from the method signature that the method call does not affect the state of the object 15%~20%

Use final keyword skillfully

The final keyword is generally used to define constants and methods, whereas most people's understanding of final is often non-denatured, and final has a great effect on performance optimization.
For example: static int age = 10, when 10 is referenced later, there will be a field lookup procedure, and for the int type is the integer constant pool in the lookup method area, and for the final constant, the process is omitted, for example: static final int age = 10. In the place where age is used, it will be replaced directly with 10.

However, for the above optimization technique, it is only valid for the base type and string type, but not for other reference types, but it is still a good practice to add static final when declaring constants.

There is also a powerful role for the final keyword: what is the benefit of defining final for those methods that are used frequently and have been identified as final?

Say this before the implementation of the method in Java, when calling a method, the first method will be in the stack, after execution, the method out of the stack, the release of resources, and this process is actually the memory address of the transfer process, when executing the method of the stack, In fact, the execution address of the program is transferred to the memory address of the method, and before doing this, there must be the original program execution of the memory address saving process, when the method executes after the stack continues to execute the program at the saved address, and this process is the method of the call process.

Therefore, the process of invoking a method actually requires space and time, while the optimization of frequent calls to the same method is actually the use of inline methods.

In addition to the inline function, the inline function is actually a compile-time optimization, the compiler will be labeled as an inline function in its invocation directly with the entire function body to replace, which eliminates the function calls the time resources consumed, but in exchange for the target code amount of increase, So the inline optimization strategy actually takes the space-time-change strategy, and for mobile, it is very useful to use the inline function skillfully.

And if a function becomes an inline function, it is defined as final, so that when the program compiles, the compiler automatically optimizes the final function inline, then the function body is directly expanded to use when the function is called.

Summary, not the more inline function, the better, on the one hand, it does improve the efficiency of our program, and on the other hand, for excessive use of inline functions, it will be self-defeating, it is possible to make a method of the method of the larger, and for some methods of large-body method, The time of the inline expansion is likely to exceed the time of the method call, so this not only provides performance, but reduces the expected performance.

In a comprehensive way, we can provide the performance of the program with final modification for methods that are used frequently, have been identified as end states, and do not have a very small method body.

prioritize the code provided in the system instead of writing it yourself

The system built up a lot of very convenient API for us to use, such as: System, Arrays, collections, string, etc. built-in many method API, this is more convenient than our own handwriting, in addition to this, for Android, many APIs use the underlying C /c++ implementation, so more efficient than we write faster, similarly, for the system API,DVM often also use inline way to improve efficiency

Caution with Exceptions

It is not necessary to use exceptions without exception, but to perform certain actions in the form of throwing exceptions, for example, some people will interrupt certain operations with a strong throw exception. Fillinstacktrace () is executed because of throwing exceptions, and the method is to re-adjust the stack, which makes it absolutely necessary to avoid using an exception.

Welcome to add ...

Neglected optimization points for Android performance optimization

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.