Java Performance Optimization
Exception Performance. Dished out an unusual first need to create a new object. Throwable interface called the constructor call fillInStackTrace () method of the local. This method is responsible for inspection of the entire stack framework to gather tracking information. Whether the timing of abnormal dished out, it calls virtual machine loading call stack, as a new object in the central been created.
It should be used only for very wrong when, instead of controlling flow.
2. Twice not to initialize variables
Java class by calling the unique default constructor to initialize variables to a known value. All the objects are set to null, integers (byte, short, int, long) is set to 0, float and double set to 0.0, Boolean variables set to false. This extends to those of other categories of particular importance, with a new use of words to create a series of targets all automatically call the constructor like.
3. Wherever possible so that category is the Final
Markers for the final category can not be extended. In the "core Java API" in a large number of examples of this technology, such as java.lang.String. String class will be marked as the final stop developers create their own methods to achieve the length.
Further point that if the category is final, all of the methods is final. Java compiler may be all in the way (this depends on the realization of compiler). In my tests, I have seen an average increase of 50 percent.
4. Any possible use local variables
Method Invocation is part of the variables and statements calling for part of the temporary variables stored in the stack, this relatively quickly. Such as static, example (instance) variables and create new objects in a pile, which is fairly slow. Local variables optimization rely on more in-depth you are using a compiler or virtual machine.
5. Stop many petty officers in the development of the brain in the preparation of reusable and flexible code, and sometimes they have the procedures on the additional costs. Or have other when they prepared a similar code:
Public void doSomething (File file) (
FileInputStream fileIn = new FileInputStream (file);
/ / Do something
He flexible enough, but at the same time they also have more overhead. The idea behind to do is the manipulation of an InputStream, rather than a document, it should be rewritten as follows:
Public void doSomething (InputStream inputStream) (
/ / Do something
6. Multiplication and division I have too much NEE apply to Moore's Law - which statement CPU power doubling every year. "Moore's Law" that each year by the developers of the code written by the number of poor increased three times, is zoned to any of the benefits of Moore's Law.
Consider the following code:
For (val = 0; val <100000; val + = 5) (shiftX val = 8; myRaise val = 2;)
If we use the crafty displacement (bit), performance will increase sixfold. This is rewriting code:
For (val = 0; val <100000; val + = 5) (val = shiftX <<3; myRaise val = <<1;)
Instead of multiplied by 8, we use the same effect of the left 3. Each mobile equivalent multiplied by 2, myRaise variables that have been made. The same right divided by the equivalent of 2 translocation, of course, it would speed up the implementation, but might make your NEE after difficult to understand, so this is just a suggestion
7. Use code to deal effectively with memory overflow
OutOfMemoryError memory is not generally after the problems encountered, the following piece of code can effectively judge memory overflow errors, and memory overflow in force at the time of recovery of memory through this method can think of the effective management of connection pool overflow of the same reason.
Import java.util .*;
Public class DataServer
(
Private Hashtable data = new Hashtable ();
Public Object get (String key)
(
Object obj = data.get (key);
If (obj == null)
(
System.out.print (key + "");
Try
(
/ / Simulate getting lots of data
Obj = new Double [1000000];
Data.put (key, obj);
)
Catch (OutOfMemoryError e)
(
System.out.print ( "\ No Memory!");
FlushCache ();
Obj = get (key); / / try again
)
)
Return (obj);
)
Public void flushCache ()
(
System.out.println ( "Clearing cache");
Data.clear ();
)
Public static void main (String [] args)
(
DataServer ds = new DataServer ();
Int count = 0;
While (true) / / infinite loop for test
Ds.get ( "" + count);
)
)
8. Lazy Loading (Lazy evaluation) needs when it loaded into
Static public long
Factorial (int n) throws IllegalArgumentException
(
IllegalArgumentException illegalArgumentException =
New IllegalArgumentException ( "must be> = 0");
If (n <0) (
Throw illegalArgumentException;
) Else if ((n 0) | | (n 1)) (
Return (1);
) Else (
Return (n factorial * (n - 1));
)
Optimized code
Static public long
Factorial (int n) throws IllegalArgumentException
(
If (n <0) (
Throw new IllegalArgumentException ( "must be> = 0");
) Else if ((n 0) | | (n 1)) (
Return (1);
) Else (
Return (n factorial * (n - 1));
)
9. Anomaly in the local needs dished out dished out, try catch can integrate on integration
Try (
Some.method1 (); / / Difficult for javac
) Catch (method1Exception e) (/ / and the JVM runtime
/ / Handle exception 1 / / to optimize this
) / / Code
Try (
Some.method2 ();
) Catch (method2Exception e) (
/ / Handle exception 2
)
Try (
Some.method3 ();
) Catch (method3Exception e) (
/ / Handle exception 3
)
Has been under the code more easily compiler optimization
Try (
Some.method1 (); / / Easier to optimize
Some.method2 ();
Some.method3 ();
) Catch (method1Exception e) (
/ / Handle exception 1
) Catch (method2Exception e) (
/ / Handle exception 2
) Catch (method3Exception e) (
/ / Handle exception 3
)
10. For the optimization cycle
Replace…
For (int i = 0; i <collection.size (); i + +) (
…
)
With…
For (int i = 0, n = collection.size (); i <n; i + +) (
…
)
11. String operation optimization in the implementation of the + string operation, it is best to use a phrase
/ / Your source code looks like…
String str = "profit = revenue (" revenue
"- Cost (the" cost "";
/ / Build method
String str = new StringBuffer (). Append ( "profit = revenue (").
Append (revenue). Append ( "- cost (").
Append (cost). Append ( ""). ToString ();
In the loop in the string operation to switch to StringBuffer.append () method
String sentence = "";
For (int i = 0; i <wordArray.length; i + +) (
WordArray sentence + = [i];
)
Optimization for
StringBuffer buffer = new StringBuffer (500);
For (int i = 0; i <wordArray.length; i + +) (
Buffer.append (wordArray [i]);
)
String sentence = buffer.toString ();
12. Object reuse (particularly for the target group)
Public
Class Point
(
Public int x;
Public int y;
Public Point ()
(
This (0, 0);
)
)
Optimization:
Public class Component
(
Private int x;
Private int y;
Public Point getPosition ()
(
Point rv = new Point () / / Create a new Point
Rv.x = x; / / Update its state
Rv.y = y;
Return rv;
)
)
/ / Process an array of Component positions…
For (int i = 0; i <componentArray.length; i + +) (
Point position [i] = componentArray. GetPosition ();
/ / Process position value…
/ / Note: A Point object is created for each iteration
/ / Of the loop…
)
May again be optimized, and use only one type object:)
Public
Class Component
(
Private int x;
Private int y;
Public Point getPosition (Point rv)
(
If (rv == null) rv = new Point ();
Rv.x = x; / / Update its state
Rv.y = y;
Return rv;
)
/ / Create a single point object and reuse it…
Point p = new Point ();
For (int i = 0; i <componentArray.length; i + +) (
Point position [i] = componentArray. GetPosition (p);
/ / Process position value…
/ / Note: Only one Point object is ever created.
)
13. Related j2ee
A) so as not to put large objects or other HttpSession sequence of the object, and pay attention to timely empty Session
B) The use of pre-compiler statements prepareStatement replace createStatement
C) If possible, using a connection pool
D) to use on the use of Cache Cache, achieving specific reference jive
Tags: Performance
Releated Java Articles
Comments
Leave a Reply
Java performance optimization!
Java performance optimization!
First, avoid the use of complex cyclic conditions expression
Not optimizing compiler in the circumstances, in the cycle, cycle conditions would be repeated, if we do not use complex expression due to the conditions of the same cycle, and will be running faster.
Examples:
Import java.util.Vector;
(Class CEL
?? Void method (Vector vector) (
???????? For (int i = 0; i <vector.size (); i ++)??// Violation
????????????; / / …
????}
)
Corrections:
(Class CEL_fixed
?? Void method (Vector vector) (
Int size = ???????? vector.size ()
???????? For (int i = 0; i <size; i + +)
????????????; / / …
????}
)
Second, 'Vectors' and' Hashtables' definition of the initial size
JVM for the expansion of the size of Vector time need to re-create a greater array, the original original copy of the contents of the array over, finally, the original array to be recycled. Vector capacity expansion that is a time-consuming task.
Usually, the default size of 10 elements is not enough. The best you can accurately estimate what you need the best size.
Examples:
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.
)
Corrections:
Set their 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
Third, finally closed in the block Stream
Procedures for the use of the resources that should be released in order to avoid leakage of resources. This best in the finally block it. Regardless of the result of the implementation procedures, and finally the implementation of the block will always be to ensure that resources are correctly closed.
?????????
Examples:
Import java.io. *;
(Public class CS
?? Public static void main (String args []) (
???????? CS cs = new CS ();
???????? Cs.method ();
????}
?? Public void method () (
Try (????????
???????????? FileInputStream fis = new FileInputStream ( "CS.java");
???????????? Int count = 0;
???????????? While (fis.read ()! = -1)
???????????????? Count + +;
???????????? System.out.println (count);
???????????? Fis.close ();
????????} Catch (FileNotFoundException e1) (
????????} Catch (IOException e2) (
????????}
????}
)
?????????
Corrections:
In the final after a catch finally add a block
References:
Peter Haggar: "Practical Java - Programming Language Guide."
Addison Wesley, 2000, pp.77-79
Fourth, the use of 'System.arraycopy ()' instead passed to the array replication cycle
'System.arraycopy ()' reproduction cycle than through an array of more than fast.
?????????
Examples:
Public class IRB
(
?? Void method () (
???????? Array1 int [] = new int [100];
???????? For (int i = 0; i <array1.length; i + +) (
???????????? Array1 [i] = i;
????????}
???????? Array2 int [] = new int [100];
???????? For (int i = 0; i <array2.length; i + +) (
???????????? Array2 [i] = array1 [i ];?????????????????// Violation
????????}
????}
)
?????????
Corrections:
Public class IRB
(
?? Void method () (
???????? Array1 int [] = new int [100];
???????? For (int i = 0; i <array1.length; i + +) (
???????????? Array1 [i] = i;
????????}
???????? Array2 int [] = new int [100];
???????? System.arraycopy (array1, 0, array2, 0, 100);
????}
)
?????????
References:
Http://www.cs.cmu.edu/ ~ jch / java / speed.html
5, access to the instance variables within the getter / setter methods become "final"
Simple getter / setter methods should be home as final, which will tell the compiler, this method will not be heavy-duty, therefore, can be turned into "inlined"
Examples:
(Class MAF
?? Public void setSize (int size) (
?????????_ Size = size;
????}
?? Private int _size;
)
Corrections:
(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 unwanted instanceof operator
If the object of the left is the right type of static, never to return instanceof expression true.
?????????
Examples :?????????
(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 uiso = u;
???????? If (uiso instanceof Object) / / always true.
???????????? System.out.println ( "uiso is an Object");
????}
)
?????????
Corrected :?????????
Delete unwanted instanceof operator.
?????????
(Class Dog extends UISO
?? Void method () (
???????? Dog d;
???????? System.out.println ( "Dog is an UISO");
???????? System.out.println ( "UISO is an UISO");
????}
)
7. Avoid unnecessary operation modeling
All categories are directly or indirectly inherited from Object. Similarly, all sub-categories are hidden "equivalent" of his father. Then, from father to son of modeling such as the operation is unnecessary.
Examples:
(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.
????}
)
?????????
Corrected :?????????
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 Effective Java. "? Addison-Wesley, 1999. Pp.22-23
8, if it is only by a single character, with charAt () instead startsWith ()
With a character as a parameter called startsWith () will work well, but from the perspective of performance, with String API call is wrong!
?????????
Examples:
(Public class PCTS
?? Private void method (String s) (
???????? If (s.startsWith ( "a")) (/ / violation
????????????// …
????????}
????}
)
?????????
Corrected ?????????
Will be 'startsWith ()' replace '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. Shift operation to replace the use of 'a / b' operation
"/" Is a very "expensive" operation, the use of shift will be faster and more efficient.
Examples:
(Public class SDIV
?? Public static final int NUM = 16;
?? Public void calculate (int a) (
???????? Int div = a / 4 ;????????????// should be replaced with "a>> 2."
???????? Int div2 = a / 8 ;?????????// should be replaced with "a>> 3."
???????? Int temp = a / 3;
????}
)
Corrections:
(Public class SDIV
?? Public static final int NUM = 16;
?? Public void calculate (int a) (
???????? Int div = a>> 2;?
???????? Int div2 = a>> 3;
???????? Int temp = a / 3 ;???????// displacement can not be converted into operation
????}
)
10 translocation operation to replace the use of 'a * b'
Ibid.
[I] However, I personally think that, except in a very large circle, the performance is very important, and you very clearly what you are doing you only use this method. Otherwise improve performance by the late Reading program will be a reduction in the uneconomical.
Examples:
(Public class SMUL
?? Public void calculate (int a) (
???????? Int mul = a * 4 ;????????????// should be replaced with "a <<2."
???????? Int mul2 = 8 * a ;?????????// should be replaced with "a <<3."
???????? Int temp = a * 3;
????}
)
Corrections:
Package OPT;
(Public class SMUL
?? Public void calculate (int a) (
???????? Int mul = a <<2;?
???????? Int mul2 = a <<3;
???????? Int temp = a * 3 ;???????// not allowed to change
????}
)
11. String together in the time, the use of '' instead of "" If only one of the string of characters
Examples:
(Public class STR
?? Public void method (String s) (
???????? String string = s + "d "??// violation.
???????? String = "abc" + "d "??????// violation.
????}
)
Corrections:
A character string will be replaced by ''
(Public class STR
?? Public void method (String s) (
???????? String string = s + 'd'
???????? String = "abc" + 'd'??
????}
)
12, not in the loop in the call synchronized (sync) method
The synchronization method consumes considerable information, in a cycle of calling it is not a good idea.
Examples:
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 vector = new Vector (5, 5);
)
Corrections:
Not in the loop of the synchronization method call, if they must be synchronized, recommend the following:
Import java.util.Vector;
(Public class SYN
?? Public void method (Object o) (
????}
Private void test () (
?? Synchronized (/ / synchronous block in the implementation of a non-synchronization method
???????????? For (int i = 0; i <vector.size (); i + +) (
???????????????? Method (vector.elementAt (i ));???
????????????}
????????}
????}
?? Private Vector vector = new Vector (5, 5);
)
13, will try / catch blocks out of circulation
To try / catch block Add to cycle in, it will greatly affect the performance of JIT compiler if you were closed or used by the JIT is not a band of the JVM, performance will drop as much as 21%!
?????????
Examples :?????????
Import java.io.FileInputStream;
(Public class TRY
?? Void method (FileInputStream fis) (
???????? For (int i = 0; i <size; i + +) (
???????????? Try {???????????????????????????????????? — / / violation
????????????????_ Fis.read sum + = ();
????????????} Catch (Exception e) ()
????????}
????}
?? Private int _sum;
)
?????????
Corrected :?????????
Will try / catch blocks out of circulation ?????????
?? Void method (FileInputStream fis) (
Try (????????
???????????? For (int i = 0; i <size; i + +) (
????????????????_ Fis.read sum + = ();
????????????}
????????} Catch (Exception e) ()
????}
?????????
References:
Peter Haggar: "Practical Java - Programming Language Guide."
Addison Wesley, 2000, pp.81 - 83
14, boolean values, avoid unnecessary equation judgement
Will be a boolean value with a true comparison is a constant, and other operations (direct return to the boolean variable value). Remove unnecessary for boolean operators will bring at least two benefits:
1) faster implementation of the code (generated bytecode five fewer bytes);
2) the code will become more clean.
Examples:
Public class UEQ
(
?? Boolean method (String string) (
???????? Return string.endsWith ( "a") == true ;???// Violation
????}
)
Corrections:
Class UEQ_fixed
(
?? Boolean method (String string) (
???????? Return string.endsWith ( "a");
????}
)
15, the constant string with 'String' instead of 'StringBuffer'
Dynamic string constants do not need to change the length.
Examples:
(Public class USC
?? String method () (
???????? StringBuffer s = new StringBuffer ( "Hello");
???????? String t = s + "World!";
???????? Return t;
????}
)
Corrections:
StringBuffer replaced by the String, the String if it is determined that will not change, it will reduce operational costs to improve performance.
16, with 'StringTokenizer' instead of 'indexOf ()' and 'substring ()'
In many of the strings in the application are not uncommon. Use indexOf (), and substring () to easily lead to a string of StringIndexOutOfBoundsException. StringTokenizer used to analyze the string category will be easier, efficiency will be higher.
Examples:
(Public class UST
?? Void parseString (String 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, the conditions of use of alternative operator "if (cond) return; else return" structure
Operators at the more simple examples:
Public class IF (
?? Public int method (boolean isDone) (
???????? If (isDone) (
???????????? Return 0;
????????} Else (
???????????? Return 10;
????????}
????}
)
Corrections:
Public class IF (
?? Public int method (boolean isDone) (
???????? Return (isDone? 0: 10);
????}
)
18. Conditions operator instead of "if (cond) a = b; else a = c;" Structure
Examples:
(Public class IFAS
?? Void method (boolean isTrue) (
???????? If (isTrue) (
????????????_ Value = 0;
????????} Else (
????????????_ Value = 1;
????????}
????}
?? Private int _value = 0;
)
Corrections:
(Public class IFAS
?? Void method (boolean isTrue) (
????????_ Value = (isTrue? 0: 1 );???????// compact expression.
????}
?? Private int _value = 0;
)
19, not in the loop in the case of variable -
In the case of the cycle of temporary variable will be increased memory consumption
Examples :?????????
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);
????????}
????}
)
?????????
Corrected :?????????
In the definition of variables in vitro cycle, and the repeated use ?????????
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 to determine the capacity of StringBuffer
StringBuffer constructor creates a default size (usually 16), an array of characters. In use, if in excess of this size, will be re-allocate memory, the creation of a greater array, and an array of copying from the original, then discarding the old array. In most cases, you can create StringBuffer a specific size, so as not enough time in the capacity of automatic growth in order to improve performance.
Examples :?????????
(Public class RSBC
?? Void method () (
???????? StringBuffer buffer = new StringBuffer (); / / violation
???????? Buffer.append ( "hello");
????}
)
?????????
Corrected :?????????
StringBuffer provide for the size of sleep. ?????????
(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, as far as possible, the use of stack variables
If the need for frequent visits to a variable, then you need to consider the scope of the variables. Static? Local, or instance variables? Visit static variables and instance variables will be more than the cost to local variables 2-3 clock cycle.
?????????
Examples:
(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 + [i] = value;
????????}
????}
?? Private int _sum;
?? Private static int _staticSum;
}?????
?????????
Corrected :?????????
If possible, use local variables as your frequently visited variables.
You can use the following method to modify getSum () method :?????????
Void getSum (int values []) (
?? Int sum = _sum ;??// temporary local variable.
?? For (int i = 0; i <value.length; i + +) (
Sum + = ???????? value [i];
????}
????_ Sum = sum;
)
?????????
Reference :?????????
Peter Haggar: "Practical Java - Programming Language Guide."
Addison Wesley, 2000, pp.122 - 125
22, do not always take the use of anti-operator (!)
Take anti-operators (!) Procedures to reduce the readability, so do not always use.
Examples:
(Public class DUN
?? Boolean method (boolean a, boolean b) (
???????? If (! A)
???????????? Return! A;
???????? Else
???????????? Return! B;
????}
)
Corrections:
Do not use if possible take-operator (!)
23, and an interface instanceof operator
Based on the design of interface is usually a good thing, because it allows the realization of a different, and remain flexible. Wherever possible, an object instanceof operator to determine whether a particular interface than it is a certain type faster.
Examples:
(Public class INSOF
?? Private void method (Object o) (
???????? If (o instanceof InterfaceBase) (}??// better
???????? If (o instanceof ClassBase) (}???// worse.
????}
)
Class ClassBase ()
Interface InterfaceBase ()
Posted on 2006-06-02 14:33 Web 2.0 technical resources to read (390) Comments (1) edit their collections quoted Category: JAVA
Tags: Performance






