To get right to the point: When is it better to use single &
or single |
as opposed to their short-circuit &&
and ||
variants?
I can't seem to find an example where it would be better to evaluate both sides of a boolean expression.
To get right to the point: When is it better to use single &
or single |
as opposed to their short-circuit &&
and ||
variants?
I can't seem to find an example where it would be better to evaluate both sides of a boolean expression.
As you have implied, you realize the difference between the short-circuit operators &&
and ||
, and the non-short-circuit operators &
and |
. But when would the difference become significant? When the second expression has a side effect or is a long-running operation that impacts performance. The easiest example of a side effect would be a method call that happens to return a boolean
, e.g.:
if (firstOperation() & secondOperation()) //...
When you need to ensure that the side effects take place, then don't short-circuit. But I don't see it in practice often, because it's clearer to call the methods with side effects first, then evaluate the condition, e.g.:
boolean first = firstOperation();
boolean second = secondOperation();
if (first && second) //...
Usually you will see the short-circuiting operators, which avoid evaluating the second operand if unnecessary. This comes in handy when the second condition has no side effects, and it can become important if the second condition involves a large overhead cost.