Описание тега short-circuiting
When executing code, the result of evaluating of a compound condition - one that is comprised of multiple logical parts, eg A OR (B AND C)
- may be known before all parts are known.
For example, if it is known that A
is true
, the result of evaluating A OR B
is true
regardless of the value of B
. In languages the support it, eg Java, the runtime environment can short circuit the evaluation at some point earlier than the end if the runtime can determine that the overall result will not be affected by any following evaluations within the compound condition.
Generally speaking, short circuits may be made in one of two conditions:
A OR B
whenA
istrue
(the result is alwaystrue
)A AND B
whenA
isfalse
(the result is alwaysfalse
)
This feature gives performance benefits and runtime safety.
Performance
If the second part of the compound condition is expensive to execute, but only relevant if some other condition applies, the expense can be avoided when appropriate. Consider this (java) code:
if (orderObject.isConfirmed() && orderObject.calculateShippingRouteLength() > 1000) {
display("Your address is too far away");
return;
}
The expensive call to calculateShippingRouteLength()
is avoided unless the order is confirmed.
Safety
Consider what would happen if this java condition was not short circuited:
if (string != null && string.contains("foo"))
If string
is null
and the evaluation was not short circuited, a NullPointerException
would be thrown when the second half was evaluated.