Precise Java Google
Home  | J2SE  | J2EE  | Book  | Free Books  | Contact
Collections  | StringAndStringBuffer  | Serialization  | IO  | Objects  | Loops  | Exceptions

Performance improvement techniques in loops

 

This topic illustrates the performance improvement techniques in loops with the following sections:

Overview of loops

Loops provide efficient way for repeating a piece of code as many times as required. Java has three types of loop control structures they are : for loop, while loop and do-while loop. The for loop is used when we know in advance how many iterations are required. The while loop is used when we do not know in advance the number of iterations required so each time before entering the loop the condition is checked and if it is true then the loop is executed. The do-while loop is always executed at least once and then the condition is checked at the end of the loop. Loops have a considerable effect on the performance of the program let us look at some points that focus on optimizing while using the loop control structures.

This section examples are tested on Windows millennium, 320mb RAM and JDK 1.3

Note: This section assumes that reader has some basic knowledge of Java loops.

Optimization techinques in loops

  • Always use an int data type as the loop index variable whenever possible because it is efficient when compared to using byte or short data types. because when we use byte or short data type as the loop index variable they involve implicit type cast to int data type.
  • When using arrays it is always efficient to copy arrays using System.arraycopy() than using a loop. The following example shows the difference

package com.performance.loop;

// This class tests the loop copy versus System.arraycopy()

public class loopTest1{

public static void main(String s[]){

                          long start,end;

int[] a=new int[2500000];

int[] b= new int[2500000];

for(int i=0;i<a.length;i++){

a[i]=i;

start=System.currentTimeMillis();

                            for(int j=0;j<a.length;j++){

b[j]=a[j];

}

end=System.currentTimeMillis();

System.out.println(end-start + " milli seconds for loop copy ");

                          int[] c= new int[2500000];

start=System.currentTimeMillis();

System.arraycopy(a,0,c,0,c.length);

end=System.currentTimeMillis();

System.out.println(end-start + " milli seconds for System.arraycopy() ");

}

}

 

The output is

110 milli seconds for loop copy

50 milli seconds for System.arraycopy()

  • Always avoid anything that can be done outside of the loop like method calls, assigning values to variables, or testing for conditions .
  • Method calls are very costly and you only make it worse by putting them in a loop. So as far as possible avoid method calls in a loop.
  • It is better to avoid accessing array elements in a loop the better option would be to use a temporary variables inside the loop and modify the array values out of the loop. It is fast to use a variable in a loop than accessing an array element.
  • Try to compare the terminating condition with zero if you use non-JIT or HotSpot virtual machine, here is an example to prove the point. JIT or HotSpot virtual machines are optimized for general loops so you do not have to bother about the terminating condition.

package com.performance.loop;

// Note that this class may give different results in latest JDK versions as discussed above.

 public class loopTest2{

public static void main(String s[]){

long start,end;

int[] a=new int[2500000];

start=System.currentTimeMillis();

for(int i=0;i<a.length;i++){

a[i]+=i;

}

end=System.currentTimeMillis();

System.out.println(end-start + " millis with i<a.length ");

                        

                        int[] b=new int[2500000];

                        start=System.currentTimeMillis();

for(int i=b.length-1;i>=0;i--){

b[i]+=i;

}

end=System.currentTimeMillis();

System.out.println(end-start + " millis with i>=0");

}

}

The output is

100 millis with i<250000

60 millis with i>=0

  • Avoid using method calls in loops for termination condition this is costly instead use a temporary variable and test the loop termination with the temporary variable.
  • When using short circuit operators to test for loop termination tests always put the expression that will most likely evaluate to false at extreme left.This saves all the following expressions from being tested in case there is an && operator and if there are only || operators then put the expression which is most likely to evaluate to true in the extreme left.
  • Avoid using try-catch inside the loops instead place the loops inside the try-catch for better performance

Key Points

  1. Use integer as loop index variable.
  2. Use System.arraycopy() to copy arrays.
  3. Avoid method calls in loops .
  4. It is efficient to access variables in a loop when compared to accessing array elements.
  5. Compare the termination condition in a loop with zero if you use non-JIT or HotSpot VMs.
  6. Avoid using method calls to check for termination condition in a loop
  7. When using short circuit operators place the expression which is likely to evaluate to false on extreme left if the expresion contains &&.
  8. When using short circuit operators place the expression which is likely to evaluate to true on extreme left if the expresion contains only ||.
  9. Do not use exception handling inside loops.

 

Feed back

We appreciate and welcome your comments on this section. Email commentsZZZ@precisejavaZZZ.com (remove ZZZ which is placed to prevent spam). Please note that we may not be able to reply to all the emails due to huge number of emails that we receive but we appreciate your comments and feedback.

 





Copyright © 2001-2005, Ravi Kalidindi and Rohini Kalidindi. All rights reserved.