簡體   English   中英

為什么在這段來自有效Java的示例代碼中使用布爾邏輯運算符^?

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

我在Joshua Bloch的書《 Effective Java》中找到了此示例代碼 旨在說明為什么您應該避免不必要地創建對象:

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();
    }
}

為什么在這里main方法內的for循環中使用布爾邏輯運算符^

是否會因為結果相同而阻止編譯器優化后續迭代(從而損害度量)?

您的猜測可能是正確的。 最后的^=運算符和if語句都是為了防止編譯器/運行時優化。

最初, b為false, b ^= trueb賦true,然后b ^= trueb賦false,循環繼續進行。

通過使b遍歷是非,將使編譯器更難優化此函數,因為它看不到恆定值。

^另一個特性是必須對兩個操作數求值才能求結果,與||不同 && 運行時不能使用快捷方式。

最后的if語句告訴編譯器和運行時:“不要忽略b !稍后使用非常重要!”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM