Will the java compiler optimize a method call on a final static variable? And what happens when it becomes dalvik code?

advertisements

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 ?


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...