Java Code Optimization Guidelines
Use Early Initialization ( Preallocated Objects) when large number of Objects are needed during CPU intensive Operations. You can create them before hand when the CPU is less loaded.
Use Lazy initialization (delay object creation until the last possible moment) when only few objects are used although many possible objects can be created.
Use local variables rather than instance or static variables for faster manipulation.
(The java compiler can assign the exact location of a local variable within the stack frame of the method at compile time which attributes to its fast access, the exact location of Object fields are not known until the class and all its super classes are loaded in to the JVM. This means that object fields can’t be accessed directly in the generated code, but require a lookup. This “late binding” is a feature of java that allows a superclass to change without requiring a recompile of all its subclasses.
Method calls in loops are costly. Try moving them out of the loop if possible or inline them. Also avoid using method calls in the loop termination test.
Declare constants as static final
If you declare x=10 but never change the value of x, it would be better to declare it as:
static final int x=5;
This allows JVM to replace references to x with constant values in the code.
Also declare method arguments final if they are not modified in the method.
String Initialization
The piece of code:
String s1 = new String (“XYZ”)
is 10 times slower than:
String s1 = “XYZ”
This is because a String is an immutable class. Hence there is no need to create a new object.
Use available runtime checks
If errors are expected to be rare, don't waste time doing an application-level check where the runtime is already doing a check for you, eg ArrayIndexOutOfBoundsException.
Since this check is going to be done whether you like it or not, you could use this to break loops rather than an explicit check of some other loop conditional. For example, instead of this:

0 Comments:
Post a Comment
<< Home