对于 VS Foreach on Array 性能(在 AS3/Flex 中) [英] For VS Foreach on Array performance (in AS3/Flex)

查看:24
本文介绍了对于 VS Foreach on Array 性能(在 AS3/Flex 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个更快?为什么?

var messages:Array = [.....]

// 1 - for
var len:int = messages.length;
for (var i:int = 0; i < len; i++) {
    var o:Object = messages[i];
    // ...
}

// 2 - foreach
for each (var o:Object in messages) {
    // ...
}

推荐答案

从我坐的位置来看,常规 for 循环比 for each 循环要快一些最小的情况.此外,与 AS2 天一样,通过 for 循环递减您的方式通常会提供非常小的改进.

From where I'm sitting, regular for loops are moderately faster than for each loops in the minimal case. Also, as with AS2 days, decrementing your way through a for loop generally provides a very minor improvement.

但实际上,这里的任何细微差别都会与您在循环内实际执行的操作的要求相形见绌.您可以找到在任何一种情况下都会更快或更慢的操作.真正的答案是,不能说任何一种循环都比另一种循环更快——您必须按照代码在应用程序中出现的方式对其进行分析.

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.

示例代码:

var size:Number = 10000000;
var arr:Array = [];
for (var i:int=0; i<size; i++) { arr[i] = i; }
var time:Number, o:Object;

// for()
time = getTimer();
for (i=0; i<size; i++) { arr[i]; }
trace("for test: "+(getTimer()-time)+"ms");

// for() reversed
time = getTimer();
for (i=size-1; 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");

结果:

for test: 124ms
for reversed test: 110ms
for each test: 261ms

为了改进比较,我更改了内部循环,以便它们只访问集合值.

To improve the comparison, I changed the inner loops so they do nothing but access the collection value.

编辑 2:对 oshyshko 评论的回答:

Edit 2: Answers to oshyshko's comment:

  1. 编译器可以跳过我内部循环中的访问,但事实并非如此.如果是这样,循环退出的速度会快两到三倍.
  2. 您发布的示例代码中的结果发生了变化,因为在该版本中,for 循环现在具有隐式类型转换.为了避免这种情况,我将作业排除在循环之外.当然,有人可能会争辩说,在 for 循环中进行额外的转换是可以的,因为无论如何真正的代码"都需要它,但对我来说,这只是另一种说法没有通用的答案;这循环更快取决于您在循环中执行的操作".这就是我给你的答案.;)
  1. 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.
  2. The results change in the sample code you posted because in that version, the for 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 for 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. ;)

这篇关于对于 VS Foreach on Array 性能(在 AS3/Flex 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆