Iterator 类和 foreach 构造之间的性能差异
我正在运行以下代码,但有时在运行它时会出现某种并发异常。
ArrayList<Mob> carriers = new ArrayList<Mob>();
ArrayList<Mob> mobs = new ArrayList<Mob>();
...
for (Mob carrier : carriers){
for (Mob mob : mobs){
checkInfections (carrier, mob);
}
}
我重构它来解决并发问题,但这确实让我产生了一个问题。如果我将 for 构造更改为迭代器模式,性能是否会有所不同? foreach 构造和 Iterator 类之间的访问级别差异是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
区别主要在于语法糖,除了
Iterator
可以从它正在迭代的Collection
中删除项目。从技术上讲,增强的for
循环允许您循环遍历任何Iterable
的内容,其中至少包括Collection
和数组。不用担心性能差异。这种微观优化是一种无关紧要的干扰。如果您需要随时删除项目,请使用
迭代器
。否则for
循环往往被更多地使用,因为它们更具可读性,即:vs:
The difference is largely syntactic sugar except that an
Iterator
can remove items from theCollection
it is iterating. Technically, enhancedfor
loops allow you to loop over anything that'sIterable
, which at a minimum includes bothCollection
s 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
. Otherwisefor
loops tend to be used more just because they're more readable ie:vs:
在幕后,新样式
for
是由编译器以迭代器的形式实现的,因此如果您自己这样做,不会有什么区别。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.您所说的“某种并发异常”很可能是java.util.ConcurrentModificationException。之所以会出现这种情况,是因为在迭代列表时无法更改列表;如果这样做,迭代器会注意到并抛出此异常。
如果您需要在迭代列表时从列表中删除元素,请通过迭代器上的
remove()
方法来完成,例如:(注意:您不能将 foreach 语法用于在这种情况下循环,因为您需要显式访问迭代器)。
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:(Note: You can't use the foreach syntax for the loop in this case, because you need explicit access to the iterator).
您只能在 List、Set 等集合上使用 Iterator(interface)。队列但对于每个循环都可用于可迭代的所有内容,例如集合和数组。并且每个循环都更具可读性..
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..