Performance difference between Iterator Class and foreach construct

浪子不回头ぞ 提交于 2019-12-19 20:24:14

问题


I have the following code running, but I sometimes get some sort of concurrency exception when running it.

ArrayList<Mob> carriers = new ArrayList<Mob>();
ArrayList<Mob> mobs = new ArrayList<Mob>();
...
for (Mob carrier : carriers){
    for (Mob mob : mobs){
        checkInfections (carrier, mob);
    } 
}

I refactored it to solve the concurrency problem, but it did lead me to a question. Would there be a difference in performance if I change the for construct to an Iterator pattern? What's the access level difference between the foreach construct and the Iterator class?


回答1:


The difference is largely syntactic sugar except that an Iterator can remove items from the Collection it is iterating. Technically, enhanced for loops allow you to loop over anything that's Iterable, which at a minimum includes both Collections and arrays.

Don't worry about performance differences. Such micro-optimization is an irrelevant distraction. If you need to remove items as you go, use an Iterator. Otherwise for loops tend to be used more just because they're more readable ie:

for (String s : stringList) { ... }

vs:

for (Iterator<String> iter = stringList.iterator(); iter.hasNext(); ) {
  String s = iter.next();
  ...
}



回答2:


Behind the scenes the new style for is implemented in terms of iterators by the compiler, so there will be no difference if you do that yourself.




回答3:


The "some sort of concurrency exception" you're talking about is most likely java.util.ConcurrentModificationException. You get this because you cannot change the list while you are iterating over it; if you do that, the iterator will notice and throw this exception.

If you need to remove elements from a list while iterating over it, then do it through the remove() method on the iterator, for example:

List<String> list = ...; // wherever you get this

for (Iterator<String> iter = list.iterator(); iter.hasNext(); ) {
    String s = iter.next();
    if (...) {
        iter.remove(); // Remove element through iterator
    }
}

(Note: You can't use the foreach syntax for the loop in this case, because you need explicit access to the iterator).




回答4:


You can use Iterator(interface) only on collections like List, Set & Queue but for each loop cab be used for everything which is iterable like Collections and Array. And for each loop is more readable..



来源:https://stackoverflow.com/questions/3183153/performance-difference-between-iterator-class-and-foreach-construct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!