Java performance optimization, java performance optimization authoritative guide

Source: Internet
Author: User

Java performance optimization, java performance optimization authoritative guide
Author: Chan Lou wangyue (http://www.cnblogs.com/yaoyinglong)

Note: The test results vary with the computer configurations !!!

1. Define the initialization size for some sets

List, Set, and Map all have a default initialization size, but this value is often not enough for our use. At this time, the JVM will apply for a larger memory for the Set, then, copy the data in the original collection, and finally the original collection will be reclaimed as garbage. Obviously, resizing is a very troublesome task, so it is best to accurately estimate the optimal size you need.

[+] View code

Public ClassCeceoptimization {

Public  Static  VoidMain (String [] args ){ LongStart = NewDate (). getTime (); List <String> a = NewArrayList <String> (); For( IntI = 0; I <1000000; I ++) {a. add ("");} LongEnd = NewDate (). getTime (); System. Out. Println (end-start); // 47 }}

After optimization:

[+] View code

Public ClassCeceoptimization {

Public  Static  VoidMain (String [] args ){ LongStart = NewDate (). getTime (); List <String> a = NewArrayList <String> (1000000 ); For( IntI = 0; I <1000000; I ++) {a. add ("");} LongEnd = NewDate (). getTime (); System. Out. Println (end-start); // 32 }}

As a result, the effect is quite impressive.

2. When copying an array, use System. arraycopy instead of circular copy, which is more efficient and concise. [+] View code

Public ClassCeceoptimization {

Public  Static  VoidMain (String [] args ){ Int[] Array1 = New  Int[100]; For( IntI = 0; I <array1.length; I ++) {array1 [I] = I ;} Int[] Array2 = New  Int[2, 100]; System. Arraycopy(Array1, 0, array2, 0, array1.length) ;}} 3. avoid unwanted instanceof operations

If the static type of the object on the left is equal to that on the right, the instanceof expression returns true forever.

[+] View code

Public ClassDogExtendsUiso {

VoidMethod (Dog dog, Uiso u) {Dog d = dog; If(D InstanceofUiso) // always true. System. Out. Println ("dog is a uiso"); Uiso uiso = u; If(Uiso InstanceofObject) // always true. System. Out. Println ("uiso is an object") ;}} 4. Avoid unwanted styling operations

All classes are directly or indirectly inherited from objects. Similarly, all child classes are implicitly "equal to" parent classes. Therefore, the operations from subclass modeling to parent class are unnecessary. For example:

Class dog extends unc

Dog = new dog ();

Unc animal = (unc) dog; // not necessary

Object o = (object) dog; // not necessary

5. If you only search for a single character, use charAt () instead of startsWith [+] view code

Public ClassCeceoptimization {

Public  VoidMethod (String s ){ If(S. startsWith ("a") {// violation //...}}
}

Replace 'startswith 'with 'charat ()'

[+] View code

Public ClassCeceoptimization {

Public  VoidMethod (String s ){ If('A' = s. charAt (0 )){//...}}
} 6. Use the shift operation to replace the 'A/B 'and 'a * B' operations.

"/" And "*" are both very expensive operations. Using shift operations will be faster and more effective.

[+] View code

Public ClassCeceoptimization {

Public  Static  Final  Int  Num= 16; Public  VoidCalculate ( IntA ){ IntDiv = a/4; // shocould be replaced with "a> 2 ". IntDiv2 = a/8; // shocould be replaced with "a> 3 ". IntTemp = a/3; // cannot be converted to a displacement operation}

}

 

Public  ClassCeceoptimization { Public  Static  Final  Int  Num= 16; Public  VoidCalculate ( IntA ){ IntMul = a * 4; // shoshould be replaced with "a <2 ". IntMul2 = 8 * a; // shocould be replaced with "a <3 ". IntTemp = a * 3; // cannot be converted to a displacement operation
}}

Note: unless it is in a very large loop, performance is very important, and you are very clear about what you are doing, you can use this method. Otherwise, it is not cost-effective to reduce the program readability caused by performance improvement.

7. Do not call in a loop Synchronized(Synchronous) Method

Method synchronization consumes a considerable amount of resources. It is definitely not a good idea to call it in a loop.

[+] View code

Public ClassCeceoptimization {

Public  Synchronized  VoidMethod (Object o ){} Private  VoidTest (){ For( IntI = 0; I <vector. size (); I ++) {method (vector. elementAt (I); // violation }} PrivateVector vector = NewVector (5, 5 );
}

Correction: do not call the synchronization method in the loop body. If synchronization is required, the following method is recommended: [+] view code

Public ClassCeceoptimization {

Public  VoidMethod (Object o ){} Private  VoidTest (){ Synchronized( This) {// Execute the non-synchronous method in a synchronization Block For( IntI = 0; I <vector. size (); I ++) {method (vector. elementAt (I ));}}}
PrivateVector vector = NewVector (5, 5 );
} 8. Remove the try/catch Block from the loop

Putting the try/catch Block into the loop will greatly affect the performance. If the jit compilation is disabled or you are using a jvm without jit, the performance will be reduced by as much as 21%!

[+] View code

Public ClassCeceoptimization {

VoidMethod (FileInputStream FS ){ For( IntI = 0; I <100; I ++ ){ Try{// Violation _ sum + = Fi. read ();} Catch(Exception e ){}}} Private  Int_ Sum;} 9. Avoid unnecessary equality judgment for boolean values

Comparing a boolean value with a true value is a constant operation (directly returning the value of this boolean variable). Removing unnecessary operations on a boolean value brings at least two benefits:

1) code execution is faster (the generated byte code is less than 5 bytes );
2) the code is also cleaner. [+] View code

Public ClassCeceoptimization {

BooleanMethod (String string) {// return string. endsWith ("a") = true; // violation ReturnString. endsWith ("");}
} 10. For constant strings, use 'string' instead of 'stringbuffer'

Constant strings do not need to change the length dynamically. Replace stringbuffer with string. If you confirm that the string will not change, this will reduce the running overhead and improve the performance.

11. Use 'stringtokenizer 'to replace 'indexof ()' and 'substring ()'

String analysis is common in many applications. Using substring () to analyze strings can easily lead to java. lang. StringIndexOutOfBoundsException. Using the StringTokenizer class to analyze strings is easier and more efficient.

12. Use a ternary expression to replace the "if (cond) XXX; else XXX;" structure. 13. Try not to instantiate variables in the loop body

Instantiating temporary variables in the loop body will increase memory consumption.

14. Use stack variables as much as possible

If a variable needs to be accessed frequently, you need to consider the scope of the variable. Static? Local? Or instance variables? Accessing static variables and instance variables is much longer than accessing local variables.

[+] View code

Public ClassCeceoptimization {

VoidGetsum ( Int[] Values ){ For( IntI = 0; I <values. length; I ++) {_ sum + = values [I]; // violation .}} VoidGetsum2 ( Int[] Values ){ For( IntI = 0; I <values. length; I ++ ){ _ Staticsum+ = Values [I]; // violation .}} Private  Int_ Sum; Private  Static  Int  _ Staticsum;
}

Correction: if possible, use local variables as the variables you frequently access. You can modify the getsum () method as follows: [+] view code

VoidGetsum (Int[] Values ){

IntSum = _ sum; // temporary local variable. For( IntI = 0; I <values. length; I ++) {sum + = values [I];} _ sum = sum;} 15. Perform the instanceof operation with an interface

Interface-based design is usually a good thing because it allows different implementations while maintaining flexibility. If possible, perform the instanceof operation on an object to determine whether an interface is faster than a class.

16. reduce repeated variable calculation as much as possible

For example

For (int I = 0; I <list. size (); I ++)

Change

For (int I = 0, len = list. size (); I <len; I ++) 17. Consider using static methods

If you do not need to access the external object, make your method a static method. She will be called faster because she does not need a virtual function directing table. This is also a good practice, because she tells you how to distinguish the nature of the method, calling this method will not change the object state.

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.