Is it more efficient to use a flag or an if clause?

advertisements

In a Java loop, is it more efficient to use a boolean flag instead of an if statement?

Take a look at these two bits of code.

Using a flag:

public boolean isSomethingForAnyone() {
    boolean flag = false;
    for (Item item : listOfItems) {
        flag = flag || item.isSomething();
    }
    return flag;
}

Using an if statement:

public boolean isSomethingForAnyone() {
    for (Item item : listOfItems) {
        if (item.isSomething())
            return true;
    }
    return false;
}

The method with the if statement is of course faster if isSomething() return true on the first iteration. But, is it faster on average or does the branching slow it down enough that it is slower? Also, is the situation different if the loop is faster? Here I used a for-each loop for simplicity, which I believe is slower than iterating over an array with a counter.


The two pieces of code aren't quite equivalent.

Even though you only call item.isSomething() as many times as you need to (contrary to my original answer), the first version still keeps trying to iterate over the rest of the collection.

Imagine an implementation of Item.isSomething() which modified the collection in which the item is found (if it returns true). At that point, the first piece of code would throw a ConcurrentModificationException assuming it's a "regular" collection - whereas the second piece of code would just return true.

Fundamentally, the second piece of code is more efficient: it only iterates through as much of the list as is required to determine the answer, instead of through everything. It may well be that the performance different is irrelevant - particularly if the collection is small - but that depends on the context.

Which you find more readable is a different matter - it's likely that the efficiency won't be significant, although that depends on the context. Personally I find the second version more readable as well as more efficient, so I'd always use it. (Well, I'd add braces around the body of the if statement, but that's all.)