Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference between Iterator Class and foreach construct

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?

like image 832
allan Avatar asked Feb 27 '23 17:02

allan


1 Answers

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();
  ...
}
like image 105
cletus Avatar answered Mar 01 '23 09:03

cletus