Friday, May 30, 2014

Advanced For Loop/Iterator/Simple Loop

At times we are left with Dilemmas.For me, one of it was the following. which of the iteration methods is the best way?
1) Advanced For Loop
2) Iterator
3) Simple Loop.
Which of them performs the best?

List<Person> personList = new ArrayList<Person>();

Advanced For Loop

for(Person currentPerson: personList){
System.out.println(currentPerson.getName());
}

Iterator

Iterator it= personList.iterator();
while(it.hasNext){
currentPerson = it.next();
System.out.println(currentPerson.getName());
}

Simple Loop

int size = personList.size();
for(int i=0;i<size;i++){
System.out.println(personList.get(i).getName());
}

Classical wisdom tells that Advanced for Loop or Iterator works best(i mean when performance alone is taken into consideration).
I too thought advanced For Loop would be the winner  till today!!
Many forums support this view. so i also believed it and i just wanted to see if advanced for loop or Iterator is the best method. My boss is a fan of Advanced For Loop so i wanted to prove him wrong and make myself better.
And the winner is .......... SIMPLE LOOP
I couldn't believe it, i refactored code as much as i could. but it still gave the same result.
Amused as i was. i couldn't believe it. so i took a look under the hood.