Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've had this discussion with a few collegues before, and we have all found different results for different scenarios. However, there was one test that I found quite eloquent for comparison's sake:</p> <pre><code>var array:Array=new Array(); for (var k:uint=0; k&lt;1000000; k++) { array.push(Math.random()); } stage.addEventListener("mouseDown",foreachloop); stage.addEventListener("mouseUp",forloop); /////// Array ///// /* 49ms */ function foreachloop(e) { var t1:uint=getTimer(); var tmp:Number=0; var i:uint=0; for each (var n:Number in array) { i++; tmp+=n; } trace("foreach", i, tmp, getTimer() - t1); } /***** 81ms ****/ function forloop(e) { var t1:uint=getTimer(); var tmp:Number=0; var l:uint=array.length; for(var i:uint = 0; i &lt; l; i++) tmp += Number(array[i]); trace("for", i, tmp, getTimer() - t1); } </code></pre> <p>What I like about this tests is that you have a reference for both the key and value in each iteration of both loops (removing the key counter in the "for-each" loop is not that relevant). Also, it operates with Number, which is probably the most common loop that you will want to optimize that much. And most importantly, the winner is the "for-each", which is my favorite loop :P</p> <p>Notes:</p> <p>-Referencing the array in a local variable within the function of the "for-each" loop is irrelevant, but in the "for" loop you do get a speed bump (75ms instead of 105ms):</p> <pre><code>function forloop(e) { var t1:uint=getTimer(); var tmp:Number=0; var a:Array=array; var l:uint=a.length; for(var i:uint = 0; i &lt; l; i++) tmp += Number(a[i]); trace("for", i, tmp, getTimer() - t1); } </code></pre> <p>-If you run the same tests with the Vector class, the results are a bit confusing :S</p>
    singulars
    1. This table or related slice is empty.
    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. 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.
 

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