問題描述
在遍歷 ArrayList、HashMap 和其他集合時,比較傳統(tǒng)的 for 循環(huán)與 Iterator 是否有任何性能測試結(jié)果?
Is there any performance testing results available in comparing traditional for loop vs Iterator while traversing a ArrayList,HashMap and other collections?
或者只是為什么我應(yīng)該使用迭代器而不是 for 循環(huán),反之亦然?
Or simply why should I use Iterator over for loop or vice versa?
推薦答案
假設(shè)這就是你的意思:
// 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),迭代器更快.對于數(shù)組和 ArrayList,性能差異應(yīng)該可以忽略不計.
Iterator is faster for collections with no random access (e.g. TreeSet, HashMap, LinkedList). For arrays and ArrayLists, performance differences should be negligible.
我相信微基準測試是萬惡之源,就像早期優(yōu)化一樣.但話又說回來,我認為對這些微不足道的事情的含義有一種感覺是件好事.因此我運行了一個小測試:
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 個隨機"字符串
- 總結(jié)它們的長度(只是為了避免編譯器優(yōu)化整個循環(huán))
- 使用所有 3 種循環(huán)樣式(迭代器、for each、for with counter)
結(jié)果與 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.
這篇關(guān)于Java 中傳統(tǒng) for 循環(huán)與 Iterator/foreach 的性能對比的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!