当我在 Java Hotspot 客户端中运行我的计时测试程序时,我得到了一致的行为。但是,当我在 Hotspot 服务器中运行它时,我得到了意想不到的结果。本质上,在我试图复制的某些情况下,多态性的成本高得令人无法接受。
这是热点服务器的已知问题/错误,还是我做错了什么?
测试程序和时间如下:
Intel i7, Windows 8
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)
Mine2: 0.387028831 <--- polymorphic call with expected timing
Trivial: 1.545411765 <--- some more polymorphic calls
Mine: 0.727726371 <--- polymorphic call with unexpected timing. Should be about 0.38
Mine: 0.383132698 <--- direct call with expected timing
随着我添加额外的测试,情况变得更糟。列表末尾附近的测试时间完全关闭。
interface canDoIsSquare {
boolean isSquare(long x);
}
final class Trivial implements canDoIsSquare {
@Override final public boolean isSquare(long x) {
if (x > 0) {
long t = (long) Math.sqrt(x);
return t * t == x;
}
return x == 0;
}
@Override public String toString() {return "Trivial";}
}
final class Mine implements canDoIsSquare {
@Override final public boolean isSquare(long x) {
if (x > 0) {
while ((x & 3) == 0)
x >>= 2;
if ((x & 2) != 0 || (x & 7) == 5)
return false;
final long t = (long) Math.sqrt(x);
return (t * t == x);
}
return x == 0;
}
@Override public String toString() {return "Mine";}
}
final class Mine2 implements canDoIsSquare {
@Override final public boolean isSquare(long x) {
// just duplicated code for this test
if (x > 0) {
while ((x & 3) == 0)
x >>= 2;
if ((x & 2) != 0 || (x & 7) == 5)
return false;
final long t = (long) Math.sqrt(x);
return (t * t == x);
}
return x == 0;
}
@Override final public String toString() {return "Mine2";}
}
public class IsSquared {
static final long init = (long) (Integer.MAX_VALUE / 8)
* (Integer.MAX_VALUE / 2) + 1L;
static long test1(final canDoIsSquare fun) {
long r = init;
long startTimeNano = System.nanoTime();
while (!fun.isSquare(r))
++r;
long taskTimeNano = System.nanoTime() - startTimeNano;
System.out.println(fun + ": " + taskTimeNano / 1e9);
return r;
}
static public void main(String[] args) {
Mine mine = new Mine();
Trivial trivial = new Trivial();
Mine2 mine2 = new Mine2();
test1(mine2);
test1(trivial);
test1(mine);
long r = init;
long startTimeNano = System.nanoTime();
while (!mine.isSquare(r))
++r;
long taskTimeNano = System.nanoTime() - startTimeNano;
System.out.println(mine + ": " + taskTimeNano / 1e9);
System.out.println(r);
}
}