Insert static functions in Java

First code :

public static int pitagoras(int a, int b)
{
    return (int) Math.sqrt(a*a + b*b);
}

public static int distance(int x, int y, int x2, int y2)
{
    return pitagoras(x - x2, y - y2);
}

distancecalled very often. When I compiled it with javacand then decompiled with javap -c, I got this bytecode:

public static int pitagoras(int, int);
  Code:
   0:   iload_0
   1:   iload_0
   2:   imul
   3:   iload_1
   4:   iload_1
   5:   imul
   6:   iadd
   7:   i2d
   8:   invokestatic    #24; //Method java/lang/Math.sqrt:(D)D
   11:  d2i
   12:  ireturn

public static int distance(int, int, int, int);
  Code:
   0:   iload_0
   1:   iload_2
   2:   isub
   3:   iload_1
   4:   iload_3
   5:   isub
   6:   invokestatic    #34; //Method pitagoras:(II)I
   9:   ireturn

It seems that javacnot optimize the second function distance.

The second code , I think, is faster:

public static int distance(int x, int y, int x2, int y2)
{
    return (int) Math.sqrt((x - x2) * (x - x2) + (y - y2) * (y - y2));
}

And its bytecode:

public static int distance(int, int, int, int);
  Code:
   0:   iload_0
   1:   iload_2
   2:   isub
   3:   iload_0
   4:   iload_2
   5:   isub
   6:   imul
   7:   iload_1
   8:   iload_3
   9:   isub
   10:  iload_1
   11:  iload_3
   12:  isub
   13:  imul
   14:  iadd
   15:  i2d
   16:  invokestatic    #24; //Method java/lang/Math.sqrt:(D)D
   19:  d2i
   20:  ireturn

Is it invokestaticso fast that it is the same as inserting a static function? Why javacnot optimize this? Or maybe this is actually optimized, and these two codes will give the same thing, but am I missing something?

+5
source share
5 answers

javacnot optimized. This is the task of implementing the JVM (usually HotSpot).

javac , , HotSpot .

HotSpot ( , "", "" ).

, javac , , .

+7

Java . (, ) Just-In-Time (JIT) ( ) .

+4

, , JVM JIT .

+1

, (), , , Just in Time (JIT) .

, , , , , .

+1

: javac , .

, distance() , . , pitagoras(), , .

, Hotspot , . , Hotspot , , . , Hotspot , , - .

, javac : . :

public class Test {
public final static boolean ENABLED=false;

public static void main(String... args) { 
  if(ENABLED)
    System.out.println("Hello World");
  }
}

- :

public static void main(java.lang.String[]);
  Code:
   0:   return

= > javac , println .

+1

All Articles