第一个代码:
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);
}
distance
经常被调用。当我用它编译它javac
然后用它反编译时,javap -c
我得到了这个字节码:
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
似乎javac
没有优化第二个功能,distance
.
我认为第二个代码更快:
public static int distance(int x, int y, int x2, int y2)
{
return (int) Math.sqrt((x - x2) * (x - x2) + (y - y2) * (y - y2));
}
及其字节码:
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
是不是invokestatic
快到和内联静态函数一样?为什么javac
没有优化这个?或者它实际上是经过优化的,这两个代码会给出相同的结果,但我错过了什么?