I. Avoid using complex expressions in loop Conditions
Without compilation optimization, loop conditions are repeatedly calculated in a loop. If the value of the loop condition remains unchanged without complex expressions, the program runs faster.
Example:
Import java. util. vector;
Class cel {
Void method (vector ){
For (INT I = 0; I <vector. Size (); I ++) // Violation
;//...
}
}
Correction:
Class cel_fixed {
Void method (vector ){
Int size = vector. Size ()
For (INT I = 0; I <size; I ++)
;//...
}
}
2. Define the initial size for 'vectors 'and 'hashtables'
When JVM expands the vector size, it needs to re-create a larger array, copy the content in the original array, and finally recycle the original array. It can be seen that the expansion of vector capacity is quite time-consuming.
Generally, the size of the default 10 elements is insufficient. You 'd better accurately estimate the optimal size you need.
Example:
Import java. util. vector;
Public class DIC {
Public void addobjects (object [] O ){
// If length> 10, vector needs to expand
For (INT I = 0; I <O. length; I ++ ){
V. Add (o); // capacity before it can add more elements.
}
}
Public vector v = new vector (); // No initialcapacity.
}
Correction:
Set the initial size.
Public vector v = new vector (20 );
Public hashtable hash = new hashtable (10 );
References:
Dov bulka, "Java performance and scalability Volume 1: server-side Programming
Techniques "Addison Wesley, ISBN: 0-201-70429-3 pp.55-57
3. Disable stream in the finally Block
The resources used in the program should be released to avoid resource leakage. This should be done in finally blocks. Regardless of the execution result of the program, the Finally block is always executed to ensure that the resource is properly closed.
Example:
Import java. Io .*;
Public class CS {
Public static void main (string ARGs []) {
CS cs = new CS ();
CS. Method ();
}
Public void method (){
Try {
Fileinputstream FCM = new fileinputstream ("CS. Java ");
Int COUNT = 0;
While (FCM. Read ()! =-1)
Count ++;
System. Out. println (count );
FCM. Close ();
} Catch (filenotfoundexception E1 ){
} Catch (ioexception E2 ){
}
}
}
Correction:
Add a Finally block after the last catch
References:
Peter Haggar: "Practical Java-programming language guide ".
Addison Wesley, 2000, pp.77-79
4. Use 'System. arraycopy () 'instead of repeating the Array
'System. arraycopy () 'is much faster than copying arrays through loops.
Example:
Public class IRB
{
Void method (){
Int [] array1 = new int [100];
For (INT I = 0; I <array1.length; I ++ ){
Array1 [I] = I;
}
Int [] array2 = new int [2, 100];
For (INT I = 0; I <array2.length; I ++ ){
Array2 [I] = array1 [I]; // Violation
}
}
}
Correction:
Public class IRB
{
Void method (){
Int [] array1 = new int [100];
For (INT I = 0; I <array1.length; I ++ ){
Array1 [I] = I;
}
Int [] array2 = new int [2, 100];
System. arraycopy (array1, 0, array2, 0,100 );
}
}
References:
Http://www.cs.cmu.edu /~ Jch/Java/speed.html
5. Change the getter/setter method used to access the variable in the instance to "final"
A simple getter/setter method should be set to final, which tells the compiler that this method will not be overloaded, so it can be changed to "inlined"
Example:
Class MAF {
Public void setsize (INT size ){
_ Size = size;
}
Private int _ size;
}
Correction:
Class daf_fixed {
Final public void setsize (INT size ){
_ Size = size;
}
Private int _ size;
}
References:
Warren N. and Bishop P. (1999), "Java in practice", p. 4-5
Addison-Wesley, ISBN 0-201-36065-9
6. Avoid unnecessary 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.
Example:
Public class uiso {
Public uiso (){}
}
Class dog extends uiso {
Void method (Dog dog, uiso U ){
DOG d = dog;
If (d instanceof uiso) // always true.
System. Out. println ("dog is a uiso ");
Uiso = u;
If (uiso instanceof object) // always true.
System. Out. println ("uiso is an object ");
}
}
Correction:
Delete unnecessary instanceof operations.
Class dog extends uiso {
Void method (){
DOG d;
System. Out. println ("dog is an uiso ");
System. Out. println ("uiso is an uiso ");
}
}
7. 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.
Example:
Class UNC {
String _ id = "UNC ";
}
Class dog extends UNC {
Void method (){
Dog dog = new dog ();
UNC animal = (UNC) dog; // not necessary.
Object o = (object) dog; // not necessary.
}
}
Correction:
Class dog extends UNC {
Void method (){
Dog dog = new dog ();
UNC animal = dog;
Object o = dog;
}
}
References:
Nigel Warren, Philip BISHOP: "Java in practice-Design Styles and idioms
For valid tive Java ". Addison-Wesley, 1999. pp.22-23
8. If you only search for a single character, use charat () instead of startswith ()
Using a single character as a parameter to call startswith () also works well, but from a performance perspective, it is undoubtedly wrong to call the string Api!
Example:
Public class PCTs {
Private void method (string s ){
If (S. startswith ("A") {// Violation
//...
}
}
}
Correction
Replace 'startswith () 'with 'charat ()'.
Public class PCTs {
Private void method (string s ){
If ('A' = S. charat (0 )){
//...
}
}
}
References:
Dov bulka, "Java performance and scalability Volume 1: server-side Programming
Techniques "Addison Wesley, ISBN: 0-201-70429-3
9. Use the shift operation to replace the 'A/B 'operation
"/" Is an expensive operation. Using shift operations will be faster and more effective.
Example:
Public class sdiv {
Public static final int num = 16;
Public void calculate (int ){
Int DIV = A/4; // shocould be replaced with "A> 2 ".
Int div2 = A/8; // shocould be replaced with "A> 3 ".
Int temp = A/3;
}
}
Correction:
Public class sdiv {
Public static final int num = 16;
Public void calculate (int ){
Int DIV = A> 2;
Int div2 = A> 3;
Int temp = A/3; // cannot be converted to a displacement operation
}
}
10. replace 'a * B 'with the shift operation'
Same as above.
[I] But I personally think that this method can be used unless it is in a very large loop, the performance is very important, and you know what you are doing. Otherwise, it is not cost-effective to reduce the program's late reading performance.
Example:
Public class SMUL {
Public void calculate (int ){
Int Mul = A * 4; // shoshould be replaced with "A <2 ".
Int mul2 = 8 * A; // shocould be replaced with "A <3 ".
Int temp = A * 3;
}
}
Correction:
Package OPT;
Public class SMUL {
Public void calculate (int ){
Int Mul = A <2;
Int mul2 = A <3;
Int temp = A * 3; // cannot be converted
}
}
11. When adding strings, use ''instead of" ". If the string contains only one character
Example:
Public class STR {
Public void method (string s ){
String string = S + "D" // violation.
String = "ABC" + "D" // violation.
}
}
Correction:
Replace a character string''
Public class STR {
Public void method (string s ){
String string = S + 'D'
String = "ABC" + 'D'
}
}
12. Do not call the synchronized (synchronous) method in a loop
Method synchronization requires a considerable amount of data. It is definitely not a good idea to call it in a loop.
Example:
Import java. util. vector;
Public class SYN {
Public synchronized void method (Object O ){
}
Private void test (){
For (INT I = 0; I <vector. Size (); I ++ ){
Method (vector. elementat (I); // Violation
}
}
Private vector = new vector (5, 5 );
}
Correction:
Do not call the synchronization method in the loop body. If synchronization is required, the following method is recommended:
Import java. util. vector;
Public class SYN {
Public void method (Object O ){
}
Private void test (){
Synchronized {// execute the non-synchronous method in a synchronization Block
For (INT I = 0; I <vector. Size (); I ++ ){
Method (vector. elementat (I ));
}
}
}
Private vector = new vector (5, 5 );
}
13. 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%!
Example:
Import java. Io. fileinputstream;
Public class try {
Void method (fileinputstream FCM ){
For (INT I = 0; I <size; I ++ ){
Try {// Violation
_ Sum + = FCM. Read ();
} Catch (exception e ){}
}
}
Private int _ sum;
}
Correction:
Remove the try/Catch Block from the loop
Void method (fileinputstream FCM ){
Try {
For (INT I = 0; I <size; I ++ ){
_ Sum + = FCM. Read ();
}
} Catch (exception e ){}
}
References:
Peter Haggar: "Practical Java-programming language guide ".
Addison Wesley, 2000, pp.81-83
14. 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.
Example:
Public class ueq
{
Boolean method (string ){
Return string. endswith ("A") = true; // Violation
}
}
Correction:
Class ueq_fixed
{
Boolean method (string ){
Return string. endswith ("");
}
}
15. For constant strings, use 'string' instead of 'stringbuffer'
Constant strings do not need to change the length dynamically.
Example:
Public class USC {
String method (){
Stringbuffer S = new stringbuffer ("hello ");
String T = S + "world! ";
Return T;
}
}
Correction:
Replace stringbuffer with string. If you confirm that the string will not change, this will reduce the running overhead and improve the performance.
16th. Use 'stringtokenizer 'to replace 'indexof ()' and 'substring ()'
String analysis is common in many applications. Using indexof () and substring () to analyze strings can easily lead to stringindexoutofboundsexception. Using the stringtokenizer class to analyze strings is easier and more efficient.
Example:
Public class ust {
Void parsestring (string ){
Int Index = 0;
While (Index = string. indexof (".", index ))! =-1 ){
System. Out. println (string. substring (index, String. Length ()));
}
}
}
References:
Graig larman, Rhett Guthrie: "Java 2 Performance and idiom Guide"
Prentice Hall PTR, ISBN: 0-13-014260-3 pp. 282-283
17. Use conditional operators to replace the "If (Cond) return; else return;" Structure
Easier condition Operators
Example:
Public class if {
Public int method (Boolean isdone ){
If (isdone ){
Return 0;
} Else {
Return 10;
}
}
}
Correction:
Public class if {
Public int method (Boolean isdone ){
Return (isdone? 0: 10 );
}
}
18. Use conditional operators to replace the "If (Cond) A = B; else a = C;" Structure
Example:
Public class IFAS {
Void method (Boolean istrue ){
If (istrue ){
_ Value = 0;
} Else {
_ Value = 1;
}
}
Private int _ value = 0;
}
Correction:
Public class IFAS {
Void method (Boolean istrue ){
_ Value = (istrue? 0: 1); // compact expression.
}
Private int _ value = 0;
}
19. Do not instantiate variables in the loop body
Instantiating temporary variables in the loop body will increase memory consumption.
Example:
Import java. util. vector;
Public class loop {
Void method (vector v ){
For (INT I = 0; I <v. Size (); I ++ ){
Object o = new object ();
O = V. elementat (I );
}
}
}
Correction:
Define variables in vitro and use them repeatedly
Import java. util. vector;
Public class loop {
Void method (vector v ){
Object O;
For (INT I = 0; I <v. Size (); I ++ ){
O = V. elementat (I );
}
}
}
20. determine the capacity of stringbuffer
The stringbuffer constrtor creates a character array of the default size (usually 16. In use, if the size exceeds this value, the memory will be re-allocated, a larger array will be created, the original array will be copied, and then the old array will be discarded. In most cases, you can specify the size when creating the stringbuffer, which avoids automatic growth when the capacity is insufficient to improve performance.
Example:
Public class rsbc {
Void method (){
Stringbuffer buffer = new stringbuffer (); // Violation
Buffer. append ("hello ");
}
}
Correction:
Provides the sleep size for stringbuffer.
Public class rsbc {
Void method (){
Stringbuffer buffer = new stringbuffer (max );
Buffer. append ("hello ");
}
Private Final int max = 100;
}
References:
Dov bulka, "Java performance and scalability Volume 1: server-side Programming
Techniques "Addison Wesley, ISBN: 0-201-70429-3 P.30-31
21. 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 takes two to three more clock cycles than accessing local variables.
Example:
Public class usv {
Void getsum (INT [] values ){
For (INT I = 0; I <value. length; I ++ ){
_ Sum + = value [I]; // violation.
}
}
Void getsum2 (INT [] values ){
For (INT I = 0; I <value. length; I ++ ){
_ Staticsum + = value [I];
}
}
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:
Void getsum (INT [] values ){
Int sum = _ sum; // temporary local variable.
For (INT I = 0; I <value. length; I ++ ){
Sum + = value [I];
}
_ Sum = sum;
}
References:
Peter Haggar: "Practical Java-programming language guide ".
Addison Wesley, 2000, pp.122-125
22. do not always use the inverse operator (!)
Inverse Operator (!) Reduce program readability, so do not always use.
Example:
Public class Dun {
Boolean method (Boolean A, Boolean B ){
If (! A)
Return! A;
Else
Return! B;
}
}
Correction:
If possible, do not use the inverse operator (!)
23. 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.
Example:
Public class insof {
Private void method (Object O ){
If (O instanceof interfacebase) {}// better
If (O instanceof classbase) {}// worse.
}
}
Class classbase {}
Interface interfacebase {} (this article is reproduced from blogjava, original address: http://www.blogjava.net/fantasy/archive/2006/06/02/49934.html)