Home:ALL Converter>Efficiency of java for loops

Efficiency of java for loops

Ask Time:2012-09-12T23:31:43         Author:user1086498

Json Formatter

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

Author:user1086498,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/12391673/efficiency-of-java-for-loops
yy