To compare how short circuit evaluation logical operators, for example &&
, perform compared to bitwise evaluation logical operators, i.e. &
, I wrote this example and ran it:
package examples1;
import java.util.Scanner;
public class ShortCircuitOperatorsVSBitwiseOperators {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter A: "); boolean a = scanner.nextBoolean();
System.out.print("Enter B: "); boolean b = scanner.nextBoolean();
long startTimeShortCircuited = System.currentTimeMillis();
boolean resultShortCircuited = true;
for(long i = 0; i < 10000000000L; i++) {
resultShortCircuited = a && b;
}
long endTimeShortCircuited = System.currentTimeMillis();
System.out.println(resultShortCircuited + " in " + (endTimeShortCircuited - startTimeShortCircuited) + " milliseconds, short-circuited");
long startTimeBitwise = System.currentTimeMillis();
boolean resultBitwise = true;
for(long i = 0; i < 10000000000L; i++) {
resultBitwise = a & b;
}
long endTimeBitwise = System.currentTimeMillis();
System.out.println(resultBitwise + " in " + (endTimeBitwise - startTimeBitwise) + " milliseconds, bitwise");
scanner.close();
}
}
An example run shows the following:
java examples1/ShortCircuitOperatorsVSBitwiseOperators
Enter A: false
Enter B: true
false in 4829 milliseconds, short-circuited
false in 3276 milliseconds, bitwise
This doesn't make sense. I would expect the short circuit evaluation to be faster since it doesn't evaluate the right side of the &&
in this case if the left side was false
. What is the reason for the counter-intuitive results?