简体   繁体   English

为什么在这段来自有效Java的示例代码中使用布尔逻辑运算符^?

[英]Why is the boolean logical operator ^ being used in this piece of example code from Effective Java?

I found this example code for Joshua Bloch's book, Effective Java. 我在Joshua Bloch的书《 Effective Java》中找到了此示例代码 It's meant to demonstrate why you should avoid unnecessarily creating objects: 旨在说明为什么您应该避免不必要地创建对象:

import java.util.regex.Pattern;

// Reusing expensive object for improved performance
public class RomanNumerals {
    // Performance can be greatly improved!
    static boolean isRomanNumeralSlow(String s) {
        return s.matches("^(?=.)M*(C[MD]|D?C{0,3})"
                + "(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");
    }

    // Reusing expensive object for improved performance (Page 23)
    private static final Pattern ROMAN = Pattern.compile(
            "^(?=.)M*(C[MD]|D?C{0,3})"
                    + "(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");

    static boolean isRomanNumeralFast(String s) {
        return ROMAN.matcher(s).matches();
    }

    public static void main(String[] args) {
        int numSets = Integer.parseInt(args[0]);
        int numReps = Integer.parseInt(args[1]);
        boolean b = false;

        for (int i = 0; i < numSets; i++) {
            long start = System.nanoTime();
            for (int j = 0; j < numReps; j++) {
                b ^= isRomanNumeralSlow("MCMLXXVI");  // Change Slow to Fast to see performance difference
            }
            long end = System.nanoTime();
            System.out.println(((end - start) / (1_000. * numReps)) + " μs.");
        }

        // Prevents VM from optimizing away everything.
        if (!b)
            System.out.println();
    }
}

Why is the boolean logical operator ^ being used in the for loop inside the main method here? 为什么在这里main方法内的for循环中使用布尔逻辑运算符^

Is it to prevent the compiler from optimizing away subsequent iterations (thereby compromising the measurement), since the result would anyway be the same? 是否会因为结果相同而阻止编译器优化后续迭代(从而损害度量)?

Your guess is probably right. 您的猜测可能是正确的。 The ^= operator and the if statement at the end are both to prevent compiler/runtime optimisations. 最后的^=运算符和if语句都是为了防止编译器/运行时优化。

Initially b is false, b ^= true assigns true to b , then b ^= true assigns false to b , and the cycle continues. 最初, b为false, b ^= trueb赋true,然后b ^= trueb赋false,循环继续进行。

By making b cycle through true and false, it makes it harder for the compiler to optimise this because it doesn't see a constant value. 通过使b遍历是非,将使编译器更难优化此函数,因为它看不到恒定值。

Another property of ^ is that both operands must be evaluated in order to evaluate the result, unlike || ^另一个特性是必须对两个操作数求值才能求结果,与||不同 or && . && The runtime can't take shortcuts. 运行时不能使用快捷方式。

The if statement at the end is telling the compiler and the runtime: "don't ignore b ! It is of important use later!". 最后的if语句告诉编译器和运行时:“不要忽略b !稍后使用非常重要!”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM