Optimizing for loop in Java

1305
Mar 20, 2016

Loops are one of most expensive part of a program. If there are any unnecessary statement inside the loop, it may reduce the performance. There are various points if we care, while coding then we can improve the performance. The main focus area of optimization is to fine-tune conditions, use fast operators, object creations etc.

Focus looping boundary check condition

The code written inside the inner loop is executed large number of times. This is place that needs more optimize logic.


Extracting loop end condition, out of loop body

public class Test {
private static int counter = 0;
public static void main(String[] args) {
for(int i=0;i<getSize() ;i++) {
//logic to execute
}
System.out.println(String.format("Method Called: %d times.",counter));
}
private static int getSize() {
counter++;
return 10;
}
}
If you run above code, What do you think, What will printed at the end of for loop ? Method Called: 1 times.? NO, Method Called: 10 times.? NO, then ???

it will print Method Called: 11 times.. you know why ?


This is because for loop checks the condition even before starting loop and then for each iteration. So if we are using the list.size() size() method will called n+1 times.


We can avoid at least n number of time this method call. and we can refactor this logic as below


public class Test {
private static int counter = 0;
public static void main(String[] args) {
int length = getSize();
for(int i=0;i<length;i++) {
//logic to execute
}
System.out.println(String.format("Method Called: %d times.",counter));
}
public static int getSize() {
counter++;
return 10;
}
}

and now this will print Method Called:1 times..


comments powered by Disqus

© Copyright 2017