![](/img/trans.png)
[英]How is the JVM prevented from 'optimizing away everything' in this piece of example code from Effective 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 ^= true
为b
赋true,然后b ^= true
为b
赋false,循环继续进行。
通过使b
遍历是非,将使编译器更难优化此函数,因为它看不到恒定值。
^
另一个特性是必须对两个操作数求值才能求结果,与||
不同 或&&
。 运行时不能使用快捷方式。
最后的if语句告诉编译器和运行时:“不要忽略b
!稍后使用非常重要!”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.