java – 本地成员更快或实例成员
发布时间:2020-12-14 16:25:46 所属栏目:Java 来源:网络整理
导读:以下代码证明method1比method2更快.任何人都可以评论这种行为的原因是什么. class Trial { String _member; void method1() { for(int i=0;i30480;i++) { _member += "test"; } } void method2() { String temp=""; for(int i=0;i30480;i++) { temp += "test
以下代码证明method1比method2更快.任何人都可以评论这种行为的原因是什么.
class Trial { String _member; void method1() { for(int i=0;i<30480;i++) { _member += "test"; } } void method2() { String temp=""; for(int i=0;i<30480;i++) { temp += "test"; } _member = temp; } public static void main(String args[]) { Trial t = new Trial(); long startTime1 = System.currentTimeMillis(); t.method1(); long endTime1 = System.currentTimeMillis(); long startTime2 = System.currentTimeMillis(); t.method2(); long endTime2 = System.currentTimeMillis(); System.out.println(endTime1 - startTime1); System.out.println(endTime2 - startTime2); } } 解决方法
不,它不能证明这一点. 这取决于很多因素.当我运行此代码时,我得到了 1403 1248 所以在我的环境中,你的代码“证明”method1比method2慢. 在进行基准测试时,您需要注意缓存和JVM预热等效果. 也可以看看 > How do I write a correct micro-benchmark in Java? 欲获得更多信息. 我稍微重构了主要方法: ... static void doBenchmark() { Trial t = new Trial(); long startTime1 = System.currentTimeMillis(); t.method1(); long endTime1 = System.currentTimeMillis(); long startTime2 = System.currentTimeMillis(); t.method2(); long endTime2 = System.currentTimeMillis(); System.out.println(endTime1 - startTime1); System.out.println(endTime2 - startTime2); } public static void main(String args[]) { for (int i = 0; i < 20; i++) { doBenchmark(); System.out.println("----"); } } 这导致for循环的第一次迭代具有相似的值,但随后结果收敛并且不再显着不同: 1396 1133 ---- 1052 1070 ---- 688 711 ---- 728 726 ---- 715 709 ---- ... 甚至,有时方法1似乎更快,有时方法2 – 这很可能是由于测量不准确. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |