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

Performance of traditional for loop vs Iterator/foreach in Java(Java 中传统 for 循环与 Iterator/foreach 的性能对比)
本文介绍了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),迭代器更快.对于数组和 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)