Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 622
Gautam Avatar asked Jul 12 '12 06:07

Gautam


3 Answers

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 ;-)

like image 112
user207421 Avatar answered Nov 10 '22 01:11

user207421


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!

like image 37
danfuzz Avatar answered Nov 10 '22 02:11

danfuzz


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

like image 1
malejpavouk Avatar answered Nov 10 '22 01:11

malejpavouk