Java language Idioms
1. Cycle
In an important cycle, the method call is eliminated when the loop terminates the judgment.
For example: the
for (int i=0; i<collection.size (); i++) {...}
To replace with ...
for (int i=0; n=collection.size (); i<n;i++) {...}
Usually, move the loop index irrelevant to the outside of the loop
for (int i=0; terminal=x.length;i<terminal;i++) {X[i] = X[i]/scalea *scaleb;}
It should be:
Double scale = scaleb*scalea;for (int i=0; terminal=x.length;i<terminal;i++) {x[i] = X[i]/scale;}
2. String
Eliminate string concatenation
Always use Stringbuffter instead of string when creating long strings
Pre-allocating stringbuffer space StringBuffer sb = new StringBuffer (5000);
3. Basic data types
Use basic data types in important loops (int-type data is usually faster than long/double data)
The wrapper class for the base data type (BOOLEAN,INTEGER,ETC) is primarily used when the method parameter passed must be a reference to an object (not a basic data type)
Use the static final modifier for all constant algebraic expressions
Make constants easier to reference (the compiler computes constant expressions in advance)
4. Abnormal
Exceptions are only used for a single true error condition, such as when an exception is thrown
Throwing an exception and executing a catch code block is expensive (mainly because you get a snapshot of the line stacks when you create an exception)
Throw an exception only if the condition is really an exception
Throwing an exception begins by creating a new object.
The constructor of the Throwable interface calls the local (Native) method named Fillinstacktrace (), and the Fillinstacktrace () method checks the stack to collect call tracking information.
Whenever an exception is thrown, the VM must adjust the call stack because a new object is created during the process.
Exceptions can only be used for error handling and should not be used to control the process.
The compiler and runtime are optimized to put several method calls in a Try/catch block instead of implementing several Try/catch blocks for each method call
try{some.method1 ();//difficut for java1.4}catch (method1exception e) {Handle exception
1//To optimize this code} try{some.method2 (),//difficut for java1.4}catch (method2exception e) {Handle exception
2//To optimize this code} try{some.method3 (),//difficut for java1.4}catch (method3exception e) {Handle exception
3//To optimize this code
}
Should be written as:
try{some.method1 (); SOME.METHOD2 (); Some.method3 (); Difficut for java1.4}catch (method1exception e) {Handle exception 1}catch (Method2exception e) {Handle Exception 2}CATC H (method3exception e) {handle Exception 3}
5. Benchmark
Note that all of these techniques will vary depending on the platform and the virtual machine
One example: In some servlet containers, it is faster to pass a outputstream as a byte output
Two in other containers, the output character through a printwriter will be faster
These techniques describe the most portable recommendations.
You may need to run some benchmarks to determine what's the fastest on your platform.
6. Create an instance of a class without a new keyword
When you create an instance of a class with the new keyword, all constructors in the chain of the constructor are invoked automatically.
But if an object implements the Cloneable interface, we can call its clone () method. The Clone () method does not call any class constructors.
In situations where design patterns are used, if you create objects in Factory mode, it is simple to use the Clone () method instead to create a new object instance.
For example, the following is a typical implementation of the factory pattern:
public static Credit Getnewcredit () {Return to new Credit ();}
After optimization:
private static Credit Basecredit = new Credit (); public static Credit Getnewcredit () {return (Credit) Basecredit.clone ();}
The above ideas are also useful for array processing.
7. Using non-blocking I/O
The Java version of the lower JDK does not support non-blocking I/O APIs. To avoid I/O blocking, some applications use a method of creating a large number of threads (in better cases, a buffer pool is used). This technique can be seen in a number of applications that must support concurrent I/O flows, such as Web servers, quotes, and auction applications. However, creating a Java thread requires considerable overhead.
JDK 1.4 introduces a non-blocking I/O library (Java.nio). If the application requires the use of an older JDK, there is a package that supports non-blocking I/O.
8. Do not repeat initialization of variables
By default, when the constructor of a class is invoked, Java initializes the variable to the determined value: All objects are set to NULL, the integer variable (byte, short, int, long) is set to 0,float and the double variable is set to 0.0, and the logical value is set to False.
This should be especially noted when a class derives from another class, because when an object is created with the new keyword, all constructors in the chain of the constructor are invoked automatically.
9. Try to specify the final modifier for the class
A class with the final modifier is not derived. In the Java Core API, there are many examples of final application, such as java.lang.String. Specifying final for the string class prevents people from overwriting the length () method.
In addition, if you specify that a class is final, all methods of that class are final. The Java compiler looks for the opportunity to inline (inline) all final methods (this is related to the specific compiler implementation). This will increase performance by an average of 50%.
10. Use local variables as much as possible
The parameters passed when the method is invoked and the temporary variables created in the call are saved in the stack (stack) faster. Other variables, such as static variables, instance variables, and so on, are created in the heap (Heap) in a slower speed. In addition, local variables may be further optimized depending on the specific compiler/JVM. See Using stack variables whenever possible.
11. Multiplication and division
Consider the following code:
for (val = 0; Val < 100000 Val +=5) {Alterx = val * 8; myresult = val * 2;}
After optimization:
for (val = 0; Val < 100000; Val + 5) {Alterx = Val << 3; myresult = Val << 1;}
The modified code is no longer multiplied by 8, instead using an equivalent left 3-bit operation, with 1 bits per left being multiplied by 2. Accordingly, the right 1-bit operation is the equivalent of dividing by 2. It is worth mentioning that, although the shift operation is fast, but may make the code more difficult to understand, so it is best to add some comments.
private static Credit Basecredit = new Credit ();p ublic static Getnewcredit () {return (Credit) Basecredit.clone ();}