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

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

问题描述

以下两个循环之间的性能差异(如果有)是什么?

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

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

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

推荐答案

来自 Effective Java 作者:Joshua Bloch :

From Item 46 in Effective Java by Joshua Bloch :

for-each 循环,引入发布 1.5,摆脱混乱以及出错的机会隐藏迭代器或索引变量完全地.结果成语同样适用于集合和数组:

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);
}

当您看到冒号 (:) 时,将其读作在."因此,上面的循环读作对于元素中的每个元素 e."笔记没有性能损失用于使用 for-each 循环,甚至 for数组.事实上,它可能会提供轻微的性能优于普通在某些情况下 for 循环,因为它计算数组索引的限制只有一次.虽然你可以通过手(第 45 项),程序员不会总是这样做.

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天全站免登陆