Pages

Tuesday, January 8, 2013

Efficient way of writing foreach loop in java

We have been using foreach loop from long enough, its quick to use, but its very important to understand how we can improve the speed and take maximum out of it.

First of all we should understand how foreach runs at compiler, let's understand it using below ex. code snippet


       /** test list with 2 elements **//*
              List<String> abs = new Vector<String>();
              abs.add("Test String 1");
              abs.add("Test String 2");
             
              for(String obj : abs){
                     System.out.println("Output is : "+obj);
              }
             
At compiler end, this will work the similar way we do this in traditional way like below
The enhanced for statement has the form:
for ( Type Identifier : Expression ) Statement
If the type of Expression is an array type, T[], then the meaning of the enhanced forstatement is given by the following basic for statement:
T[] a = Expression;
for (int i = 0; i < a.length; i++) {
    Type Identifier = a[i];
    Statement
}
where a and i are compiler-generated identifiers that are distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhanced for statement occurs.
So in fact the language does guarantee that Expression will only be evaluated once.
For completeness, here's the equivalence when the Expression is of type Iterable:
The enhanced for statement has the form:
for ( Type Identifier : Expression ) Statement
If the type of Expression is a subtype of Iterable, then let I be the type of the expressionExpression.iterator(). The enhanced for statement is equivalent to a basic for statement of the form:
for (I iter = Expression.iterator(); iter.hasNext(); ) {
    Type Identifier = iter.next();
    Statement
}
where iter is a compiler-generated identifier that is distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhanced for statement occurs.
Note that it is a compile-time error if Expression is neither an Iterable nor an array, so the above two are the only cases where you can use an enhanced for loop. Also, for clarity, the above quotes leave out information regarding any labels attached on the for loop and any modifiers attached on theIdentifier, but these are handled as one would expect.


Now as we can see, the compiler will create iterator even if the list is empty, which is a heavy operation.

So better way of using for each is, first checking if the list is empty or not

If(!abs.isEmpty()){
for(String obj : abs){
                     System.out.println("Output is : "+obj);
              }

}