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?
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.