java - Is there a performance difference between a for loop and a for-each loop? -
what, if any, performance difference between following 2 loops?
for (object o: objectarraylist) { o.dosomething(); }
and
for (int i=0; i<objectarraylist.size(); i++) { objectarraylist.get(i).dosomething(); }
from item 46 in effective java joshua bloch :
the for-each loop, introduced in release 1.5, gets rid of clutter , opportunity error hiding iterator or index variable completely. resulting idiom applies equally collections , arrays:
// preferred idiom iterating on collections , arrays (element e : elements) { dosomething(e); }
when see colon (:), read “in.” thus, loop above reads “for each element e in elements.” note there no performance penalty using for-each loop, arrays. in fact, may offer slight performance advantage on ordinary loop in circumstances, computes limit of array index once. while can hand (item 45), programmers don’t so.
Comments
Post a Comment