Fork me on GitHub

Object、Array、Vector遍历性能测试

原创文章,未经允许,请勿转载

talk is cheap,show me the code!

var obj:Object = { }; 
var arrVector:Vector.<int> = new Vector.<int>(); 
var arrArray:Array = []; 

var len:int; 
var i:int; 
var key:String; 
var val:int; 
var t1:int, t2:int, t3:int, t4:int, t5:int, t6:int, t7:int, t8:int, t9:int,t10:int; 
var t11:int, t12:int, t13:int, t14:int, t15:int, t16:int, t17:int, t18:int, t19:int; 

//初始化50万个元素 
t1 = getTimer(); 
for (i = 0; i < 500000; i++)  
{ 
    obj[i] = i; 
    arrVector.push(i); 
    arrArray.push(i); 
} 
//for遍历key 
t2 = getTimer(); 
for (key in obj) 
{ 
    val = obj[key]; 
} 
//for each 遍历value 
t3 = getTimer(); 
for each(val in obj) 
{ 
    val; 
} 
//for each 遍历Vector 
t4 = getTimer(); 
for each(val in arrVector) 
{ 
    val; 
} 
//for循环Vector,length属性放for里面 
t5 = getTimer(); 
for (i = 0; i < arrVector.length; i++)  
{ 
    val = arrVector[i]; 
} 
//for循环Vector,length属性放for外面 
t6 = getTimer(); 
len = arrVector.length; 
for (i = 0; i < len; i++)  
{ 
    val = arrVector[i]; 
} 
//for each遍历Vector 
t7 = getTimer(); 
for each(val in arrVector) 
{ 
    val; 
} 
//for循环Array,length属性放for里面 
t8 = getTimer(); 
for (i = 0; i < arrArray.length; i++)  
{ 
    val = arrArray[i]; 
} 
//for循环Array,length属性放for外面 
t9 = getTimer(); 
len = arrArray.length; 
for (i = 0; i < len; i++)  
{ 
    val = arrArray[i]; 
} 
t10 = getTimer(); 

trace("1:" + (t2-t1));//288 
trace("2:" + (t3-t2));//1974 
trace("3:" + (t4-t3));//67 
trace("4:" + (t5-t4));//50 
trace("5:" + (t6-t5));//44 
trace("6:" + (t7-t6));//42 
trace("7:" + (t8-t7));//52 
trace("8:" + (t9-t8));//70 
trace("9:" + (t10-t9));//46

可以看出for遍历object获得key,然后再用obj[key]获得value的方式性能是最低的!

用Vector,然后把length提前赋值出来,再for循环是最快的!

补充:根据这篇文章 //jacksondunstan.com/articles/2514 的测试结果,在使用for in循环时,不指定key的类型,比定义string类型的key,快5倍:

// 慢! 
for (var str:String in obj) 
{ 
} 

// 比上面那种方式快 5 倍! 
for (var key:* in obj) 
{ 
}

来源:悠游悠游,原文地址:https://yymmss.com/p/202.html