[英]AS3 Array "for each ... in" performance vs. for loop, and guaranteed in order?
This question is really twofold:这个问题真的是双重的:
How does for each
looping over an Array compare performance-wise with a simple for
loop through its elements? Array 上for each
循环如何与通过其元素的简单for
循环在性能方面进行比较?
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
具有不同的集合(数组,矢量等),性能排名(从最快到最慢):
for
for each
for in
(extremely slow) for in
(极慢) In all cases for
is the fastest of all. 在所有情况下, for
都是最快的。 In particular when used with arrays or vectors, for
has an overwhelming performance. 特别是与阵列或载体一起使用时, for
具有压倒性的性能。 Those are the numbers for all collections (smaller means faster): 这些是所有集合的数字(越小意味着速度越快):
here is fixed post from Adrian这是 Adrian 的固定帖子
var size:Number = 10000000;
var arr:Array = [];
var time:Number, o:Object, i:int;
// fill container
for (i = 0; i < size; i++) arr[i] = i;
time = getTimer();
for (i=0; i<arr.length; i++){ arr[i]; }
trace("for test: "+(getTimer()-time)+"ms");
// for()
time = getTimer();
for (i=arr.length; i>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");
// Result
for test: 212ms
for reversed test: 26ms
for each test: 103ms
Please check my post Flex Array Performance: For vs. ForEach 请检查我的文章Flex Array Performance:For vs. ForEach
Some code 一些代码
var size:Number = 10000000;
var arr:Array = [];
for (var i:int=0; i
var time:Number, o:Object;
// for()
time = getTimer();
for (i=0; i=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");
Results 结果
for test: 124ms
for reversed test: 110ms
for each test: 261ms
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.