问题描述
Java编译器会优化简单的重复数学运算,例如:
Will the Java Compiler optimize simple repeated math operations like:
if (prevX / width != curX / width) {
// Do something with prevX / width value
} else {
// Do something with curX / width value
}
我知道我可以将结果分配给if语句之前的变量,然后返回变量,但这有点麻烦.如果编译器自动识别出正在执行相同的计算并将结果自己缓存到临时变量中,我宁愿遵守上述约定.
I know I can just assign the results to a variables before the if statement, and return the variables, but it's kind of cumbersome. If the compiler automatically recognizes that the same calculations are being made and caches the results to temporary variables on its own, I'd rather stick to the above convention.
*编辑-我是个白痴.我试图过多地简单/抽象我的问题.它不是简单的:if(x> y)
*Edit - I'm an idiot. I tried to simply/abstract my question too much. It's not at simple as: if (x > y)
推荐答案
答案是肯定的.这称为常见子表达式消除,它是Java中使用的标准(且功能强大)编译器优化,C/C ++和其他...
The answer is yes. This is called Common Subexpression Elimination and is a standard (and powerful) compiler optimization used in Java, C/C++ and others...
此页面确认HotSpot JVM将进行此优化.
This page confirms that the HotSpot JVM will do this optimization.
这就是说,编译器/运行时是否能够在您期望的时候进行此优化是另一回事.因此,如果可以提高可读性,我通常更愿意自己进行这些优化.
That said, whether or not the compiler/run-time will be able to do this optimization when you expect it to is another story. So I usually prefer to do these optimizations myself if it also enhances readability.
double xw = x / width;
double yw = y / width;
if (xw > yw) {
return xw;
} else {
return yw;
}
这篇关于编译器会优化重复的数学计算吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!