2

Let's take an empty List :

List<String> dummyList = new ArrayList<String>();

Now what is the difference between below two codes :

1. Using isEmpty() method

if(!dummyList.isEmpty()){
    for(String dummy : dummyList){
        System.out.println("Enhanced for loop for empty list : "+dummy);
    }
}

2. Without Using isEmpty() and relying on for-each

for(String dummy : dummyList){
    System.out.println("Enhanced for loop for empty list : "+dummy);
}

Manu times i have been asked to use the first approach rather than second.But even for-each also not traverse if list is empty.

Then what is the difference between two and which one is better to perform ?

Prateek
  • 12,014
  • 12
  • 60
  • 81
  • Depending on the situation, a check for `null` might be appropriate, since the for loop would throw an NPE on a *null* list, but the isEmpty check seems like an ugly, pointless micro-optimization to me. – Ian McLaird Oct 04 '13 at 15:10

3 Answers3

3

The first case won't implicitly create an Iterator object to use in the for-each loop.

You can say that has "better performance", but I find it uglier.

Take a look here on how the enhanced for loop is implemented. You're basically avoiding all of that if your list isEmpty.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
3
for(String dummy : dummyList){
    System.out.println("Enhanced for loop for empty list : "+dummy);
}

converts to

for(Iterator<String> i = dummyList.iterator(); i.hasNext(); ) {
  String element = i.next();

}

Iterator is checking elements are there are not here, IMHO avoid that empty check.

Performance diff almost negligible. Prefer readable code.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You're asking about List, which is an interface. The answer is going to depend on the specific implementation class that's being used.

In general I'd say that the performance of an iterator is fairly good, but there may be cases where the implementation is complex and slow while the performance of the isEmpty is probably very good.

So in general, the more readable code is just as fast as the code with the isEmpty() check, but if performance is really an issue, there will be some app-specific cases where you'll want to use isEmpty().

Chris Gerken
  • 16,221
  • 6
  • 44
  • 59