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?
Short circuited operation is complicated.
public static boolean shortCircuitedAnd(boolean a, boolean b) {
return a && b;
}
public static boolean bitwiseAnd(boolean a, boolean b) {
return a & b;
}
They are compiled to
public static boolean shortCircuitedAnd(boolean, boolean);
Code:
0: iload_0
1: ifeq 10
4: iload_1
5: ifeq 10
8: iconst_1
9: ireturn
10: iconst_0
11: ireturn
public static boolean bitwiseAnd(boolean, boolean);
Code:
0: iload_0
1: iload_1
2: iand
3: ireturn
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