我知道如果我用反射创建新对象,它很慢,所以我测试它。但结果让我感到困惑, newInstance ()比 new()更快,我的jdk版本是 java版“1.8.0_77”。
public class Test {
static class B {
}
public static long timeDiff(long old) {
return System.nanoTime() - old;
}
public static void main(String args[]) throws Exception {
int numTrials = 10000000;
B[] bees1 = new B[numTrials];
Class<B> c = B.class;
long nanos;
nanos = System.nanoTime();
for (int i = 0; i < numTrials; i++) {
bees1[i] = new B();
}
System.out.println("Normal instaniation took: " + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms");
B[] bees2 = new B[numTrials];
nanos = System.nanoTime();
for (int i = 0; i < numTrials; i++) {
bees2[i] = c.newInstance();
}
System.out.println("Reflecting instantiation took:" + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms");
}
}
结果:
所以我不知道为什么..谁能解释一下?