性能:通过Java中的List进行迭代 [英] Performance: Iterating through a List in Java
问题描述
以这样的方式迭代Java中的列表是否较慢:
for(int i = 0; i< list .size(); i ++){
.. list.get(i)
}
而不是:
for(Object o:list){
... o
}
I假设你问出纯粹的好奇心
并且不会引用Knuth(某人可能是
)。
我相信一旦你的代码被编译,它就没有什么区别。 确实在之前产生差异(示例2更具可读性和简洁性),所以请选择2号而不关心其余部分。
只需2美分
编辑
<请注意,每次循环运行时,您的代码在1号片段中计算
list.size()
,这可能会使它比数字2更慢 再次编辑
我需要仔细检查,Joshua Bloch建议使用对于每个
循环(请参阅 Effective Java 的第46项)。我认为这结束了各种讨论。谢谢乔希! :)
Is it slower to iterate through a list in Java like this:
for (int i=0;i<list.size();i++) {
.. list.get(i)
}
as opposed to:
for (Object o: list) {
... o
}
I assume you ask out of pure curiosity and won't cite Knuth (somebody probably will).
I believe that once your code gets compiled, it doesn't make a difference. It does make a difference before (example 2 is a lot more readable and concise), so go for number 2 and do not care about the rest.
Just my 2 cents
EDIT
Note your code in snippet number 1 calculates list.size()
every time the loop runs, that could make it even slower than number 2
YET ANOTHER EDIT
Something I had to double check, Joshua Bloch recommends using for each
loops (see item 46 of Effective Java). I believe that ends all kinds of discussions. Thanks Josh! :)
这篇关于性能:通过Java中的List进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!