I have the following code
float square(float val) { return val*val;}
boolean isInCircle(final float x,final float y) {
float squareDistance = square(cx - x) + square(cy - y);
return squareDistance < square(RADIUS);
}
where RADIUS
is a static
final
float
.
Will the java compiler optimize the call square(RADIUS)
?
What happens when this converted to dalvik
code for android
? Will it remain optimized ?
The Java compiler won't do anything with that code.
The HotSpot JVM will almost certainly precompute square(RADIUS).
Android doesn't have that particular JVM.
I personally wouldn't write the square() method at all, just return (cx-x)*(cx-x)+(cy-y)*(cy-y) < RADIUS*RADIUS;
and let the compiler/JVM battle it out from there. But then I'm a mathematician ;-)
The Dalvik JIT compiler does in fact inline short functions, such as square()
as defined in the question (though probably better to declare it static
). However, I couldn't tell you off-hand whether it would definitely get inlined.
Profile the code if it matters!
Optimizations in Java are done (as far as I know) by the HotSpot compiler at runtime (bytecode is optimized when translated to machine code). So the answer is yes and no.
The transformed code will be equally optimized, but it depends on JVM, what will do with it. According my experience, it is highly dependent on the JVM and probably in its setting (agressivity of the optimizer). I have tried to compare running of SHA1 with loops and without on Windows JVM and Linux one. In one case the code without loops was many times faster, in the second (I think on Linux) there was only a difference about 40% of the time taken...
So it is a magic, you might give HotSpot good hints to optimize, or configure JVM, but still, it will depend on the current algorithm of JVM...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With