Java 中传统 for 循环与 Iterator/foreach 的性能对比

2022-01-10 00:00:00 for-loop arraylist iterator java map

在遍历 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),迭代器更快.对于数组和 ArrayList,性能差异应该可以忽略不计.

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.

相关文章