Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhanced for loop empty check optimization

Tags:

java

for-loop

I know with java one shouldn't bother with things like this but I just can't resist, which is the 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);
}

The enhanced for loop does an empty check before it starts to do anything right? So using an enclosing if(empty) is totally useless?

like image 733
Ryan Marv Avatar asked Feb 12 '23 03:02

Ryan Marv


1 Answers

The enhanced for loop does an empty check before it starts to do anything right?

No, I wouldn't expect it to. I'd expect it to just create the iterator, which then won't find anything. That's what JLS 14.14.2 describes, anyway:

The enhanced for statement is equivalent to a basic for statement of the form:

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

The body of the loop will never be executed. Yes, it may create an extraneous object (the iterator) but in 99.99% of cases I'd expect that not to be a significant performance hit. (As noted, the iterator() method may return a singleton empty iterator to avoid this...)

If you have evidence that in your specific application, this gets hit very, very frequently when the collection is empty, and that all the extra iterators are causing an issue, then it's fair to micro-optimize. But I wouldn't even think about doing it before you have concrete performance figures in a realistic context.

like image 172
Jon Skeet Avatar answered Feb 15 '23 10:02

Jon Skeet