Does the java compiler optimize repeated mathematical calculations?
The java compiler optimizes simple repetitive mathematical operations, such as:
if (prevX / width != curX / width) {
// Do something with prevX / width value
} else {
// Do something with curX / width value
}
I know I can assign the result to the variable and return the variable before the if statement, but it's a little troublesome If the compiler automatically recognizes that the same calculation is in progress and caches the results in temporary variables, I'd rather adhere to the above convention
*Editor - I'm an idiot I tried to ask my question simply / abstractly This is not simple: if (x > y)
Solution
The answer is yes This is called common subexpression optimization. It is a standard (powerful) compiler optimization used in Java, C / C + +
This page confirms that the hotspot JVM will perform this optimization
That is, whether the compiler / runtime can do this optimization as you expect is another matter 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;
}
