栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java思考:为什么这么慢?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java思考:为什么这么慢?

您的测试可能有缺陷。通常,尽管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");    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/486270.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号