This question is really twofold:
How does for each
looping over an Array compare performance-wise with a simple for
loop through its elements?
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?
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):
for
for each
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):