As an addendum to this question Java loop efficiency ("for" vs. "foreach")
I have a simple question. Does the enhanced for-loop have a larger memory footprint, or will they both compile to the same construction, making their memory footprint identical and thus making for(Object o : collection) { ... } always better for read-only operations?
My reason for asking is that in a simulator I’m working on, every frame (60/sec) I am running operations against possibly thousands of items in arrays such as faces to draw, to raytrace against, etc. The loop
for(Object o : collection) {
o.doSomething();
}
Looks like it may make a memory-copy of the collection (and I seem to recall that it does from my previous reading) which is okay in most circumstances, but not if you do 30000 raytraces times 60 a second.
On the other hand, it is clear that the loop
count = collection.size();
for(i = 0; i < count; i++) {
collection[i].doSomething();
}
does everything by reference and has a relatively small footprint even though it is harder to read (though honestly, not much)
Any ideas, folks?
(Note: the impact of the difficulty to read for loops is only evident when you’re several layers in – for single layer fors the gain is extremely minor. I say this from experience… collection[i].property.subcollection[j].row[k].col[l].prop.subtable[m] gets to be a mindbreaker, especially if some of those need to be cast: ((Type3)((Type2)((Type1)collection[i]).property.subcollection[j].row[k]).col[l].prop).subtable[m] for example.)
If you have an ArrayList using hte following pattern can be a micro-optimisation
The memory you save is about 16-24 bytes as the for-each loop will always create an Iterator.
For 60,000 per second you are unlikely to notice the difference esp as you are doing relatively significant work with each item.
It doesn’t which is why you can get a ConcurrentModicationException if you change the list while looping over it. One workaround for this is to take a copy.