Optimizing for loop in Java

4202

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.

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