Tuesday 21 April 2015

Loop Optimization in java

Loop Optimization I found it very interesting thing that will increase the java looping performance
===============================================================
public loopA()
 {
     String str = “abcdefghijklmnopqurstuvwxyz”; 
    
       for (int j = 0; j < str.length(); j++) {
       }
  }
====================================================
public loopB()
 {
  String str = “abcdefghijklmnopqurstuvwxyz”;
  int len = str.length();
  for (int j = 0; j < len; j++)
   {
//This is because the length of the string is not calculated for each iteration
//through the loop. 
  }
}
====================================================
LooB is 200% faster than loopA.


This is because the length of the string is not calculated for each iteration
through the loop. The method call to str.length() is avoided by setting the results to an integer prior to entering the loop.