Java – is it more efficient to use flag or if clauses?
Is it more efficient to use Boolean flags instead of if statements in Java loops?
Look at these two lines of code
Use signs:
public boolean isSomethingForAnyone() { boolean flag = false; for (Item item : listOfItems) { flag = flag || item.isSomething(); } return flag; }
Use the if statement:
public boolean isSomethingForAnyone() { for (Item item : listOfItems) { if (item.isSomething()) return true; } return false; }
If issomething () returns true on the first iteration, the method using the if statement is certainly faster But is it faster on average, or is the branch slow enough to be slower? In addition, if the cycle is faster, will the situation be different? For simplicity, I use a for - each loop here, which I think is slower than iterating over an array using a counter
Solution
These two pieces of code are not exactly the same
Even if you only need to call item Is something () (contrary to my original answer), the first version will still try to iterate over the rest of the collection
Imagine an item An implementation of issomething (), which modifies the collection where the item is found (if it returns true) At this point, the first code will throw a concurrentmodificationexception, assuming that it is a "normal" collection - and the second code will return true
Fundamentally, the second code is more effective: it iterates only the list needed to determine the answer, not through everything It's likely that performance differences don't matter - especially if the collection is small - but it depends on the context
What you find more readable is another problem - efficiency may not be great, although it depends on the context Personally, I find the second version more readable and efficient, so I always use it (well, I'll add braces around the body of the if statement, but that's it.)