for循环和for-each循环之间是否有性能差异? [英] Is there a performance difference between a for loop and a for-each loop?

查看:134
本文介绍了for循环和for-each循环之间是否有性能差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有的话,以下两个循环之间的性能区别是什么?(b)对于(Object o:objectArrayList){b
$ b

 o.DoSomething(); 

code $

$ b $ p

$ $ p (int i = 0; i< objectArrayList.size(); i ++){
objectArrayList.get(i).DoSomething();


解决方案

href =http://rads.stackoverflow.com/amzn/click/0321356683 =noreferrer> Joshua Bloch撰写的Effective Java :



release 1.5中引入的for-each循环摆脱了
的混乱,
掩盖了迭代器或索引变量
完全。结果成语
同样适用于集合和
数组:

  //迭代的首选成语集合和数组
for(Element e:elements){
doSomething(e);

$ / code>

当您看到冒号(:)时,请将其读为
in。因此,上面的循环读取元素中每个元素e的
注意
没有使用for-each循环的性能损失
,即使对于
阵列。实际上,在某些情况下,它可能提供比普通的
for循环稍微
的性能优势,因为它
只计算一次数组索引
的限制。虽然你可以通过
(Item 45)来做到这一点,程序员不要
总是这样做。


What, if any, is the performance difference between the following two loops?

for (Object o: objectArrayList) {
    o.DoSomething();
}

and

for (int i=0; i<objectArrayList.size(); i++) {
    objectArrayList.get(i).DoSomething();
}

解决方案

From Item 46 in Effective Java by Joshua Bloch :

The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
    doSomething(e);
}

When you see the colon (:), read it as "in." Thus, the loop above reads as "for each element e in elements." Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.

这篇关于for循环和for-each循环之间是否有性能差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆