传统的绩效循环VS Java中的Iterator /的foreach [英] Performance of traditional for loop vs Iterator/foreach in Java

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

问题描述

有没有在循环迭代器VS在遍历一个ArrayList中,HashMap和其他收藏品相比传统的使用性能测试的结果?

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?

推荐答案

假设这是你的意思:

// 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是对于没有随机访问(例如TreeSet中,HashMap的,链表)的集合速度更快。对于数组和的ArrayList,性能差异可以忽略不计。

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

编辑:我认为,微基准是pretty多的邪恶根源,就像早期的优化。但话又说回来,我认为这是件好事,对于这样的相当琐碎的事情的影响的感觉。因此,我已经运行小试

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:


  • 遍历一个链表和一个ArrayList respecively

  • 10万随机字符串

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

  • 使用所有3环样式(迭代器,对于每一个,对于计数器)

结果是所有与计数器与LinkedList的相似,但。所有其他五只花了不到20毫秒来遍历整个列表。使用 list.get(我)在LinkedList的100,000次时间超过2分钟(!),完成(慢6万倍)。哇! :)因此,最好使用一个迭代器(或明或暗地使用每个),特别是如果你不知道你处理什么类型和大小的列表。

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.

这篇关于传统的绩效循环VS Java中的Iterator /的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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