java-为什么new()比newInstance()

时间:2017-11-27 03:49:47

标签: java reflection

我知道如果我用反射创建新对象,它很慢,所以我测试它。但结果让我感到困惑, 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");

}

}

结果:

  • 正常实例:2363ms
  • 反映实例化时间:1679ms。

所以我不知道为什么..谁能解释一下?

0 个答案:

没有答案