I understand the difference below (at least for Java):
if( true || false ) // short-circuiting boolean operator
if( true | false ) // non-short-circuiting boolean operator
But my question is, is there any reason to use the non-short-circuiting operator when you are dealing with boolean expressions? Is there some performance benefit or use that wouldn't be considered bad practise?
OR(||) short circuit: If there is an expression with ||(logical OR), and the first operand itself is true, a short circuit occurs, evaluation stops, and true is returned. Example: Short-circuiting using OR( || ).
The | and & logical operators, known as non-short circuit operators, should not be used. Using a non-short circuit operator reduces the efficiency of the program, is potentially confusing and can even lead to the program crashing if the first operand acts as a safety check for the second.
A short-circuit operator is used in some programming languages to execute a second argument when the first argument's outcome is not sufficient to evaluate the full expression.
The difference is that the short circuit operator doesn't evaluate the second operand if the first operand is true, which the logical OR without short circuit always evaluates both operands.
One reason you might want to use the non-short-circuiting operator is if you are somehow depending on side-effects of functions. For example.
boolean isBig(String text) {
System.out.println(text);
return text.length() > 10;
}
...
if( isBig(string1) || isBig(string2) ){
...
}
If you don't care about whether the println
is executed then you should use the short circuit operations as above. However, if you want both strings to be printed always (thus depending on side effects) then you need to use the non-short-circuit operator.
Practically speaking, you almost always want to use the short-circuit operators. Relying on side effects in expressions is usually bad programming practice.
One exception is in very low level or performance-sensitive code. The short-circuiting operators can be slightly slower because they cause branching in the program execution. Also using bitwise operators allows you to do 32 or 64 parallel boolean operations as a single integer operation, which is very fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With