Java中的传统for循环与迭代器/ foreach的性能 [英] Performance of traditional for loop vs Iterator/foreach in Java

查看:131
本文介绍了Java中的传统for循环与迭代器/ foreach的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



或者简单的说,为什么我应该使用Iterator来进行比较,比较传统的for循环与迭代器之间的性能测试结果?为了循环,反之亦然?

解决方案

假设这是你的意思:



(int i = 0; i< collection.size(); i ++){pre> //传统for循环
(int i = 0; i ++){
T obj = (一世);
// snip
}

//使用迭代器
迭代器< T> iter = collection.iterator();
while(iter.hasNext()){
T obj = iter.next();
// snip
}

//内部使用迭代器(使用javap -c确认自己)
(T obj:collection){
// snip
}

迭代器对于没有随机访问的集合(例如TreeSet, HashMap,LinkedList)。对于阵列和ArrayLists,性能差异应该是可忽略的。



编辑:我认为微基准测试是根本的邪恶,就像早期优化一样。但是再一次,我觉得对这样一个很小的事情的影响有一种感觉。因此,我已经运行一个小型测试




  • 遍历一个LinkedList和一个ArrayList,分别用100,000个随机字符串

  • 总结长度(只是一些避免编译器优化整个循环)

  • 使用所有3个循环样式(迭代器,每个为计数器)



除了with with counter与LinkedList之外,所有结果都是相似的。所有其他五个人花了不到20毫秒来遍历整个列表。在LinkedList上使用 list.get(i) 100,000次,超过2分钟(!)完成(6万次)。哇! :)因此,最好使用迭代器(显式或隐式地使用每个),特别是如果你不知道你处理的列表的类型和大小。


Is there any performance testing results available in comparing traditional for loop vs Iterator while traversing a ArrayList,HashMap and other collections?

Or simply why should I use Iterator over for loop or vice versa?

解决方案

Assuming this is what you meant:

// 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
}

Iterator is faster for collections with no random access (e.g. TreeSet, HashMap, LinkedList). For arrays and ArrayLists, performance differences should be negligible.

Edit: 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:

  • iterate over a LinkedList and an ArrayList respecively
  • with 100,000 "random" strings
  • summing up their length (just something to avoid that compiler optimizes away the whole loop)
  • using all 3 loop styles (iterator, for each, for with counter)

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.

这篇关于Java中的传统for循环与迭代器/ foreach的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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