title: Efficient loop through Java List
body: <p>The following list is from the google I/O talk in 2008 called "Dalvik Virtual Machine Internals" its a list of ways to loop over a set of objects in order from most to least efficient:</p>
  
  <pre><code>(1) for (int i = initializer; i &gt;=0; i--) //hard to loop backwards
  (2) int limit = calculate_limit(); for (int i= 0; i&lt; limit; i++)
  (3) Type[] array = get_array(); for (Type obj : array)
  (4) for (int i =0; i&lt; array.length; i++) //gets array.length everytime
  (5) for (int i=0; i &lt; this.var; i++) //has to calculate what this.var is
  (6) for (int i=0; i &lt; obj.size(); i++) //even worse calls function  each time
  (7) Iterable list = get_list(); for (Type obj : list) //generic object based iterators slow!
  </code></pre>
  
  <p>The first 3 are in the same territory of efficiency, avoid 7 if possible. This is mainly advice to help battery life but could potentially help java SE code too.</p>
  
  <p>My question is: why (7) is slow and why (3) is good? I thought it might be the difference between Array and List for (3) and (7). Also, as Dan mentioned (7) creates loads of small temporary objects which have to be GCed, I'm a bit rusty on Java nowadays, can someone explain why? It's in his <a href="http://www.youtube.com/watch?v=ptjedOZEXPM" rel="noreferrer">talk video</a> at 0:41:10 for a minute.</p>