Short circuit vs non short circuit operators

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 your code is performance sensitive enough and the operations cheap enough, using the non-short circuit can be faster. This is because using || involves performing a branch, and a branch prediction miss can be very expensive. Where as the | performs a calculation and examining a variable can be much faster, avoiding a branch prediction miss.

Note: this is a micro-optimisation that you will rarely see a difference unless it is called many, many times.


short-circuit, meaning they don't evaluate the right hand side if it that doesn't necessary. As an example if && left hand side is false no need to evaluate right hand side one. In other way || if left is true no need to evaluate right hand side one.

non-short evaluvate both side always.

Then obviously there is a benefit with short-circuit operators.

And benefit of non-short, can find an answer here.Are there good uses for non-short-circuiting logical (boolean) operators in Java/Scala?

Consider this example too

  while (status){ // status is boolean value
          if(!a | result){// a and result are boolean value
              result=getResult(); // result can change time to time
          } 
      }

we need to check both side now.

Tags:

Java