gpt4 book ai didi

java - 为什么在Effective Java 的这段示例代码中使用 boolean 逻辑运算符^?

转载 作者:行者123 更新时间:2023-11-30 01:58:15 25 4
gpt4 key购买 nike

我找到了this example code 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();
}
}

为什么是boolean logical operator ^在这里 main 方法内的 for 循环中使用?

是否是为了防止编译器优化后续迭代(从而损害测量),因为结果无论如何都是相同的?

最佳答案

你的猜测可能是对的。 ^= 运算符和末尾的 if 语句都是为了防止编译器/运行时优化。

最初 b 为 false,b ^= true 将 true 分配给 b,然后 b ^= true将 false 赋给 b,然后循环继续。

通过使 b 循环 true 和 false,编译器会更难优化它,因为它看不到常量值。

^ 的另一个属性是必须计算两个操作数才能计算结果,这与 ||&& 不同。运行时不能走捷径。

最后的 if 语句告诉编译器和运行时:“不要忽略 b!它稍后会有重要用处!”。

关于java - 为什么在Effective Java 的这段示例代码中使用 boolean 逻辑运算符^?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53690515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com