Java 中传统 for 循环与 Iterator/foreach 的性能
在遍历 ArrayList、HashMap 和其他集合时比较传统的 for 循环和 Iterator 是否有任何性能测试结果可用?
Is there any performance testing results available in comparing traditional for loop vs Iterator while traversing a ArrayList,HashMap and other collections?
或者只是为什么我应该在 for 循环上使用迭代器,反之亦然?
Or simply why should I use Iterator over for loop or vice versa?
假设这就是你的意思:
// traditional for loop
for (int i = 0; i < collection.size(); i++) {
T obj = collection.get(i);
// snip
}
// using iterator
Iterator<T> iter = collection.iterator();
while (iter.hasNext()) {
T obj = iter.next();
// snip
}
// using iterator internally (confirm it yourself using javap -c)
for (T obj : collection) {
// snip
}
对于没有随机访问的集合(例如 TreeSet、HashMap、LinkedList),迭代器更快.对于数组和 ArrayLists,性能差异应该可以忽略不计.
Iterator is faster for collections with no random access (e.g. TreeSet, HashMap, LinkedList). For arrays and ArrayLists, performance differences should be negligible.
我相信微基准测试是邪恶的根源,就像早期优化一样.但话又说回来,我认为对这些微不足道的事情的影响有一种感觉是件好事.因此我运行了一个小测试:
I believe that micro-benchmarking is root of pretty much evil, just like early optimization. But then again, I think it's good to have a feeling for the implications of such quite trivial things. Hence I've run a small test:
- 分别迭代 LinkedList 和 ArrayList
- 有 100,000 个随机"字符串
- 总结它们的长度(只是为了避免编译器优化整个循环)
- 使用所有 3 种循环样式(迭代器、for each、for with counter)
对于 LinkedList,除了for with counter"之外的所有结果都相似.所有其他五个都花费了不到 20 毫秒的时间来遍历整个列表.在 LinkedList 上使用 list.get(i)
100,000 次需要 2 多分钟 (!) 才能完成(慢 60,000 倍).哇!:) 因此最好使用迭代器(显式或隐式用于每个),尤其是当您不知道要处理的列表的类型和大小时.
Results are similar for all but "for with counter" with LinkedList. All the other five took less than 20 milliseconds to iterate over the whole list. Using list.get(i)
on a LinkedList 100,000 times took more than 2 minutes (!) to complete (60,000 times slower). Wow! :) Hence it's best to use an iterator (explicitly or implicitly using for each), especially if you don't know what type and size of list your dealing with.