Improved optimization of empty loop check

I know with java one shouldn't worry about such things, but I just can't resist, which is faster ?:

ArrayList <Integer> keke = new ArrayList();
ArrayList <Integer> kuku = new ArrayList();
if(!keke.isEmpty()){
    for(Integer num : keke){
        System.out.println(num);
    }
}

//or just:

for(Integer num : kuku){
    System.out.println(num);
}

      

An improved for loop does an empty check before it starts doing something right? So using a closing if (empty) is completely useless?

+3


source to share


2 answers


An improved for loop does an empty check before it starts doing something right?

No, I would not expect that. I expect it to just create an iterator, which then won't find anything. What JLS 14.14.2 describes anyway:

The boosted for statement is equivalent to the main expression of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
      {VariableModifier} TargetType Identifier =
          (TargetType) #i.next();
      Statement
}

      



The loop body will never be executed. Yes, it can create an extraneous object (an iterator), but 99.99% of the time I would expect it to not be a significant hit. (As noted, the method iterator()

can return a plain empty iterator to avoid this ...)

If you have evidence that in your particular application it hits very hard when the collection is empty, and that all additional iterators are causing the problem, then this holds true for micro-optimization. But I wouldn't even think about it before you have specific performance metrics in a realistic context.

+4


source


I like to write:

for(Iterator<Integer> itr = kuku.iterator(); itr.hasNext();) {
   ...
} 

      



And as you can see, it is redundant to check if it is empty, since it hasNext

will false

, and the loop will not be executed.

+3


source







All Articles