Google performance drops
Http://developer.android.com/intl/zh-cn/training/articles/perf-tips.html
This article deals with some small optimizations that can be combined to improve the overall performance of your app without significantly improving performance. It is beyond the scope of this article to improve performance by preferring appropriate algorithms and data structures. The techniques here should be used as a habit of writing code in order to write efficient code.
There are two basic rules for efficient code:
- Do not do unnecessary things
- Try not to allocate memory
Optimize the Android program when you need to face different hardware, different versions of the VMS, different processors, different speeds! The tests on the simulator rarely involve performance. Whether you have a JIT impact is also very large.
Avoid creating unnecessary objects
Object creation is not free. Garbage collection also requires cost.
If the method returns a string, the result is always added to StringBuffer, and the function implementation signature should be modified without creating a temporary object directly attached.
When extracting a string from a set of input data, return substring instead of creating a copy. This creates a new string object, but it shares char[with the input data] (the disadvantage is that if only a small fraction of the source data is used, the entire data cannot be reclaimed.) )。
Some of the more radical approaches are to cut multidimensional arrays into multiple one-dimensional arrays: int[] is more efficient than integer[.
Use static instead of virtual
If you do not need to access the members of the object and declare the method static, the call speed will be increased by 15%-20%. This is a good habit, since the method signature can be used to identify that the method call does not affect the state of the object.
Defining constants with Static final
Static int intval =; Static String strval = "Hello, world!";
The compiler generates a class initialization method <clinit>, which is called when the class is first used. This method puts 42 in Intval and assigns the reference to Strval from the class file string constant table. When you use these values later, you use fields to find (field lookup) the way.
Plus final:
Static Final int intval =; Static Final String strval = "Hello, world!";
Such a class no longer requires a <clinit> method, because constants go into the static field initializer of the Dex file (static fields initializers). Reference intval will be replaced by 42 directly.
Note: This optimization is valid only for base types and string types, not arbitrary reference types. However, it is still a good practice to add a static final prefix when declaring constants.
Avoid internal getters/setters
Native languages such as C + + often use getters (i = GetCount ()) to replace member access (i = mCount) so that the compiler can access it inline and control access rights. However, access to virtual methods on Android is more expensive than member lookup (field lookup).
member access without a JIT is about 3 times times faster than access by getter methods. Having a JIT access member variable is as inexpensive as accessing a local variable, and member access is about 7 times times faster than getter access.
Note Proguard can inline code.
Using the enhanced for loop
The enhanced for loop (also called the "For-each" loop) can be used to enumerate the collections and arrays that implement the Iterable interface. The collection allocates an iterator (iterator) object to implement the Hasnext () and Next () methods. ArrayList hand-written with the counter loop is 3 times times faster, the other set is the same efficiency.
Here are the scenarios for several common groups of iterations:
Static classFoo {intMsplat;} Foo[] Marray= ... Public voidZero () {intsum = 0; for(inti = 0; i < marray.length; ++i) {sum+=Marray[i].msplat; }} Public voidOne () {intsum = 0; Foo[] LocalArray=Marray; intLen =localarray.length; for(inti = 0; i < Len; ++i) {sum+=Localarray[i].msplat; }} Public voidBoth () {intsum = 0; for(Foo a:marray) {sum+=A.msplat; }}
Zero () is the slowest because the JIT cannot optimize the cost of getting the array length for Each loop.
One () is faster, and it copies everything needed into local variables, avoiding lookups. But only the optimization of the array length produces an effect.
Both () is the fastest on a device without a JIT, but there is no big difference between a JIT device and one (). It uses the intensive version of the For loop.
Private access using package-level access instead of internal classes
For the following code
Public classFoo {Private classInner {voidstuff () {Foo. This. Dostuff (Foo. This. Mvalue); } } Private intMvalue; Public voidrun () {Inner in=NewInner (); Mvalue= 27; In.stuff (); } Private voidDostuff (intvalue) {System.out.println ("Value is" +value); }}
The class defines an inner class (Foo$inner) that accesses private methods and private members of the outer class directly. It is illegal for a virtual machine to access Foo's private methods because they are different classes, but the Java syntax allows such access, so the Foo$inner generates dynamic methods to solve the problem.
/* Package */ Static int foo.access$100(foo foo) { return foo.mvalue;} /* Package */ Static void int value) { Foo.dostuff (value);}
Each time Foo$inner accesses a private member of Foo or a private method, it is ostensibly called directly, but is actually accessed through these static access methods, and the method call is much slower than the direct call of the member. It is best to change to public or default when defining member variables, but this exposes the members of the class, so do not do so in the open API.
Avoid using floating-point numbers
Float on Android devices is twice times slower than Int.
There is no difference in the speed of float and double on today's hardware devices, but the latter takes up twice times the space, which is not a problem for desktop space, but Android is a problem.
In addition, some machines have hardware multiplication for integer numbers, but no division. division or take-rest operations are software implementations that you need to consider when designing a hash table or doing a lot of math.
Using Library functions
The code provided in the library is preferred, and sometimes the system can use assembler code (hand-coded assembler) to replace the library method, which is more efficient than using JIT, such as String.IndexOf () and related Api,dalvik, using inline implementations. The same system.arraycopy () is 9 times times faster than a handwritten loop on a Nexus device with a JIT.
Use the native function with caution
Using the NDK-based native code is not necessarily faster than Java, because the conversion before java-native is also cost-optimized, and the JIT is unable to optimize this boundary condition. If you use local resources (native-resources, memory, files, or other), the timely recovery of resources becomes more difficult. And you have to compile the native code into a variety of racks. The NDK is typically used to migrate legacy code to the Android platform, not to "speed up" Java.
If you do need to use the native code, take a look at JNI Tips here.
About the error of performance
On devices that do not have a JIT, it is quicker to invoke a method by a specific type than by using an interface (such as calling HashMap map faster than map map, although they are actually called HashMap methods). It was said that it would be about 1 time times slower, but in fact it was only about 6% slower, and there was almost no difference on the JIT device.
In a device vendor without a JIT, access to cache members is probably 20% faster than repeated accesses, but for JIT, member access and local variables are almost no different, so this optimization doesn't mean much unless it makes your code more readable. (same as for variables with static, final, and static final modifications)
Continuous measurement
Before you begin to optimize, make sure you have a performance problem that needs to be addressed to ensure accurate measurement of your current performance, or you won't be able to figure out how much of the performance improvement has been brought about by optimization.
These standard tests are based on the Java version of the Caliper Micro-test (microbenchmarks) framework. Microbenchmarks is difficult to be accurate, so caliper helped us do this, and even detected some of the things we thought were tested but not tested (because the VMs were optimized for the code). It is highly recommended to use Caliper to run your own micro-test program.
Using Traceview is also useful, and it is important to keep in mind that the current Traceview is not JIT-enabled, so it will incorrectly estimate the JIT-led time optimization. After making changes based on TraceView data, the actual code can run faster without traceview.
Android Performance optimization