5 simple java code optimization tricks we miss during coding.

Now a days we give lot of attention to optimizing the code. Here some of the things we miss during the coding which really optimizes the code ... I have tried to list these things hope you find it useful while coding.

1. Eliminating common sub expression.

If we are using same common sub expression for calculation we can create one constant and then we can use it for multiple calculations which helps in removing redundant calculation which can affect the speed.

int a = ( multi * div1/div2) + b ;
int b = ( multi * div1/div2) + d ;

int constant = ( multi * div1/div2);
int a = ( constant ) + b ;
int a = ( constant ) + b ;

2. Avoiding same calculations in for or any loop :

If we do same calculations in loop then it takes time in doing same things again and again. So we need to take out that common calculations part outside the loop and use the same result in calculations in loop.

int c = 5;
int d = 20;
int e = 4;

int multi = 1;
int constant = ( c * ( d / e) );
long startTime = System.currentTimeMillis();
for( int i = 0 ; i < 30000 ; i++){
int start = ( constant )* multi;

3. Casting object to a local variable.

Casting object in a local variable is time saver than to repeat the cast multiple times or in a loop.

if (obj instanceof OptExample){
if ( (((OptExample)obj).val1 == this.val1 && ((OptExample)obj).val2 == this.val3) ){
//Do something here

if (obj instanceof OptExample){
OptExample oe = (OptExample)obj;
if ( (((oe).val1 == this.val1 && ((oe).val2 == this.val3) ){
//Do something here

4. Avoiding instantiating objects in loops :

Instantiating an object in loop can be expensive.If hierarchy of the object class is long ( increased abstraction ) then it results in calling more and more constructor. This ultimately results in more instantiation time.
Also garbage collection for discarded object also contribute to time consumption.
So we need to carefully check we really need to instantiate the object every time in loop or not.

5. Use strength reduction techniques :

We can replace the operation with an equivalent operation that executes faster. An example of this kind of technique is using x >> 2 in place of x / 4, and x << 1 in place of x * 2.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment