您的测试可能有缺陷。通常,尽管JVM可以优化常规实例,但不能针对反射用例进行优化。
对于那些想知道现在几点的人,我添加了一个预热阶段,并使用数组来维护创建的对象(与实际程序可能执行的 *** 作更相似)。我在OSX,jdk7系统上运行了测试代码,并得到了以下信息:
反映实例化耗时:5180ms
正常实例化耗时:2001ms
修改后的测试:
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[] bees = new B[numTrials]; Class<B> c = B.class; for (int i = 0; i < numTrials; i++) { bees[i] = c.newInstance(); } for (int i = 0; i < numTrials; i++) { bees[i] = new B(); } long nanos; nanos = System.nanoTime(); for (int i = 0; i < numTrials; i++) { bees[i] = c.newInstance(); } System.out.println("Reflecting instantiation took:" + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms"); nanos = System.nanoTime(); for (int i = 0; i < numTrials; i++) { bees[i] = new B(); } System.out.println("Normal instaniation took: " + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms"); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)