比较短路求值逻辑运算符(例如&&
(与按位求值逻辑运算符(即 &
,我写了这个例子并运行了它:
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();
}
}
示例运行显示以下内容:
java examples1/ShortCircuitOperatorsVSBitwiseOperators
Enter A: false
Enter B: true
false in 4829 milliseconds, short-circuited
false in 3276 milliseconds, bitwise
这说不通。我希望短路评估会更快,因为在这种情况下,如果左侧false
,它不会评估&&
的右侧。反直觉结果的原因是什么?
短路操作很复杂。
public static boolean shortCircuitedAnd(boolean a, boolean b) {
return a && b;
}
public static boolean bitwiseAnd(boolean a, boolean b) {
return a & b;
}
它们被编译为
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