Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>From where I'm sitting, regular <code>for</code> loops are moderately faster than <code>for each</code> loops in the minimal case. Also, as with AS2 days, decrementing your way through a <code>for</code> loop generally provides a very minor improvement.</p> <p>But really, any slight difference here will be dwarfed by the requirements of what you actually do inside the loop. You can find operations that will work faster or slower in either case. The real answer is that neither kind of loop can be meaningfully said to be faster than the other - you must profile your code as it appears in your application.</p> <p>Sample code:</p> <pre><code>var size:Number = 10000000; var arr:Array = []; for (var i:int=0; i&lt;size; i++) { arr[i] = i; } var time:Number, o:Object; // for() time = getTimer(); for (i=0; i&lt;size; i++) { arr[i]; } trace("for test: "+(getTimer()-time)+"ms"); // for() reversed time = getTimer(); for (i=size-1; i&gt;=0; i--) { arr[i]; } trace("for reversed test: "+(getTimer()-time)+"ms"); // for..in time = getTimer(); for each(o in arr) { o; } trace("for each test: "+(getTimer()-time)+"ms"); </code></pre> <p>Results:</p> <pre><code>for test: 124ms for reversed test: 110ms for each test: 261ms </code></pre> <p>Edit: To improve the comparison, I changed the inner loops so they do nothing but access the collection value.</p> <p>Edit 2: Answers to oshyshko's comment:</p> <ol> <li>The compiler could skip the accesses in my internal loops, but it doesn't. The loops would exit two or three times faster if it was.</li> <li>The results change in the sample code you posted because in that version, the <code>for</code> loop now has an implicit type conversion. I left assignments out of my loops to avoid that. Of course one could argue that it's okay to have an extra cast in the <code>for</code> loop because "real code" would need it anyway, but to me that's just another way of saying "there's no general answer; which loop is faster depends on what you do inside your loop". Which is the answer I'm giving you. ;)</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload