Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short circuit vs non short circuit operators

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?

like image 909
kin3tik Avatar asked Aug 21 '13 05:08

kin3tik


People also ask

Which is short-circuit OR operator?

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( || ).

Which operator is a non short-circuiting logical?

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.

Why are short circuit operators used?

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.

What is the difference between logical AND and short-circuit and?

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.


1 Answers

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.

like image 126
Eamonn O'Brien-Strain Avatar answered Oct 02 '22 08:10

Eamonn O'Brien-Strain