The &&
operator (as well as the ||
operator) perform shortcircuiting. That means that if you have two operands A
and B
, and A
turns out to be false
, then evaluating B
makes no sense in A && B
: regardless what the value of B
is, the result will be false
anyway.
But that does not mean you always should put slowMethod()
after fastMethod()
.
Say for instance fastMethod()
takes 0.01 seconds, but for 99.9% of the cases, the outcome is true
, and slowMethod()
takes 1.0 seconds, but is true
for 50% of the cases.
Then the fastMethod() && slowMethod()
approach will have an average runtime of:
t(fast_slow) == 0.01 + 0.999 * 1.0 = 1.009
Whereas for slowMethod() && fastMethod()
approach, we get:
t(slow_fast) = 1.0 + 0.5 * 0.01 = 1.005
Short-circuiting is not only used to boost performance. It can also be used to guard against exceptions in an elegant way. We can for instance use it as:
Object[] data = ...
if (data.length > 2 && data[2] != null) {
}
In case we did it the other way, it could raise an index out of bounds, whereas here the first condition checks if the array has enough elements.