迭代器类和foreach结构之间的性能差异 [英] Performance difference between Iterator Class and foreach construct

查看:182
本文介绍了迭代器类和foreach结构之间的性能差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码运行,但我有时在运行时会得到一些并发异常。

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?

推荐答案

差异主要是语法糖,除了$ code>迭代器可以从 Collection 中删除​​项目,它正在迭代。从技术上讲,循环中增强的允许您循环使用 Iterable 的任何内容,这至少包括集合 s和数组。

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();
  ...
}

这篇关于迭代器类和foreach结构之间的性能差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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