Search code examples
actionscript-3flash

AS3 Array "for each ... in" performance vs. for loop, and guaranteed in order?


This question is really twofold:

  1. How does for each looping over an Array compare performance-wise with a simple for loop through its elements?

  2. Does a loop guarantee in order traversal? The following code says yes:

var sample_array:Array = [];
for (var i:uint = 0; i < 10000; i++) sample_array.push(i);
i = 0;
for each(var value:uint in sample_array) {
  sample_array[i++] = value;
}

trace('in order was:', check_in_order(sample_array));

function check_in_order(array:Array):Boolean
{
  for (var i:uint = 0, l:uint = array.length; i < l; ++i) {
    if (array[i] != i) return false;
  }

  return true;
}

but I have heard other (senior-level) engineers swear up and down that the traversal does not always proceed in ascending order! Is this true?


Solution

  • As demonstrated by Jackson Dunstan, who compared for, for each and for in with different collections (arrays, vectors, etc), the performance ranking is (from fastest to slowest):

    1. for
    2. for each
    3. for in (extremely slow)

    In all cases for is the fastest of all. In particular when used with arrays or vectors, for has an overwhelming performance. Those are the numbers for all collections (smaller means faster):

    Loop Speed Redux by Jackson Dunstan