循环 ("abcdefghijklmnopqrstuvwxyz").split("")
这个数组 100000
次的结果:(单位:ms)
No. | for 循环 | for..in 循环 | for each 循环 |
---|---|---|---|
1 | 17 | 8213 | 2165 |
2 | 19 | 8126 | 2188 |
3 | 18 | 8338 | 2128 |
4 | 18 | 7100 | 2409 |
5 | 17 | 8054 | 2945 |
平均 | 17.8 | 7900.2 | 2367.0 |
偏差(越小越稳定) | 0.748 | 443.326 | 305.225 |
测试程序:
源码:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
scriptTimeLimit="10"
width="520" height="490">
<mx:Script>
<![CDATA[
private static const FOR:String = "for 循环";
private static const FOR_IN:String = "for..in 循环";
private static const FOR_EACH:String = "for each 循环"
private static var LOOP_SRC:Array = ("abcdefghijklmnopqrstuvwxyz").split("");
private function test(testCase:String):void {
var loopCount:int = int(count_ns.value);
var start:int, now:int;
var i:int;
output("@" + testCase);
try {
switch (testCase) {
case FOR:
start = getTimer();
for (i = 0; i < loopCount; i++) {
//var length:int = LOOP_SRC.length;
for(var j:int; j<LOOP_SRC.length; j++) {
LOOP_SRC[j].toUpperCase();
}
}
now = getTimer();
break;
case FOR_IN:
start = getTimer();
for (i = 0; i < loopCount; i++) {
for(var j2:String in LOOP_SRC) {
LOOP_SRC[j2].toUpperCase();
}
}
now = getTimer();
break;
case FOR_EACH:
start = getTimer();
for (i = 0; i < loopCount; i++) {
for each(var v:String in LOOP_SRC) {
v.toUpperCase();
}
}
now = getTimer();
break;
}
}
catch (e:Error) {
now = getTimer();
output(" " + i + "次时弹出错误: " + e);
}
var time:int = now - start;
output(" 经过时间(ms): " + nf.format(time));
output(" 1秒中的循环次数: " + nf.format(i * 1000 / time));
output("----------------------------------------");
}
private function output(msg:String):void {
output_ta.text += msg + "\n";
}
]]>
</mx:Script>
<mx:NumberFormatter id="nf" precision="0" />
<mx:Panel title="循环数组的压力测试"
paddingTop="8" paddingRight="8" paddingBottom="8" paddingLeft="8">
<mx:HBox>
<mx:Label text="循环回数:" />
<mx:NumericStepper id="count_ns" value="100000" maximum="10000000" />
</mx:HBox>
<mx:HBox>
<mx:Button label="{FOR}" click="test(FOR)" />
<mx:Button label="{FOR_IN}" click="test(FOR_IN)" />
<mx:Button label="{FOR_EACH}" click="test(FOR_EACH)" />
</mx:HBox>
<mx:TextArea id="output_ta" width="400" height="300" />
<mx:Label color="red" text="*Application.scriptTimeLimit设为了10秒。" />
</mx:Panel>
</mx:Application>
没有评论:
发表评论