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
}
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.
*Edit – I’m an idiot. I tried to simply/abstract my question too much. It’s not at simple as: if (x > y)
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…
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.