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);
              }

}

6 comments:

  1. Python coding online allows learners to practice real programs.It focuses on syntax and logic building.Practice strengthens fundamentals.This Python coding online supports continuous learning.It is practical.

    ReplyDelete
  2. "Enhance your career with sfdc admin course designed to equip you with hands-on Salesforce administration skills. Learn to manage users, automate processes, and optimize CRM operations effectively."

    ReplyDelete
  3. "Boost your data skills with the best tableau training designed for beginners and professionals alike. Learn to visualize, analyze, and transform data into actionable insights effectively."

    ReplyDelete
  4. EasyPayTax makes tax filing easy and stress-free with expert support, secure online processing, and accurate return submissions. GST registration in Hyderabad

    ReplyDelete
  5. EasyPayTax: smart, simple, and affordable online tax filing for individuals and businesses with professional support. tax compliance services in Hyderabad

    ReplyDelete
  6. EasyPayTax offers seamless online tax filing and expert assistance to help you meet deadlines and optimize your tax returns. online CA services in Hyderabad

    ReplyDelete