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.)