短路评估应该比按位评估更快,但事实并非如此。为什么呢?

时间:2018-04-15 05:19:26

标签: java bitwise-operators logical-operators short-circuiting

比较短路评估逻辑运算符的方式,例如&&,与按位评估逻辑运算符进行比较,即&,I写了这个例子并运行它:

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的右侧。反直觉结果的原因是什么?

1 个答案:

答案 0 :(得分:0)

短路操作很复杂。

class RetailItem:
    def __init__(self, price, units, description): 
        self.price = price
        self.units = units
        self.description = description

    def __str__(self):
        string = str(self.description)
        string += ": $" + str(self.price)
        string += " Units:" + str(self.units)
        return string


class CashRegister:
    def __init__(self):
        self.total_items = [] # Should be a List
        self.total_price = 0; # Missing

    def menu(self):
        print("Welcome to The Toy Store.\n Selection:\n 1.Bunny \n 2.Porcupine \n 3.Duck")
        choice = int(input("What would you like to buy? "))
        if choice==1:
            item = Bunny
        elif choice == 2:
            item = Porcupine
        elif choice==3:
            item = Duck
        else:
            print("Error")

    def purchase(self, item: RetailItem):
        self.total_items.append(item.description)
        self.total_price += item.price

    def get_total(self):
        print("Your total items are: ", self.total_items)

    def show_items(self):    
        print("Your total price is: ", self.total_price)

    def clear_register():
        total_price = []
        total_items = 0

它们被编译为

public static boolean shortCircuitedAnd(boolean a, boolean b) {
    return a && b;
}

public static boolean bitwiseAnd(boolean a, boolean b) {
    return a & b;
}