private static const NUM_LOOPS:int = 15;
public function VectorTest():void
{
var vector:Vector.<int> = new Vector.<int>(1000000);
var array:Array = new Array(1000000);
var sTime:Number;
sTime = getTimer();
loopArray(array);
trace("Loop Array Avg (1) : " + ((getTimer() - sTime)));
sTime = getTimer();
loopVector(vector);
trace("Loop Vector Avg (1) : " + ((getTimer() - sTime)));
sTime = getTimer();
loopArray(array, false);
trace("Loop Array Avg (2) : " + ((getTimer() - sTime)));
sTime = getTimer();
loopVector(vector, false);
trace("Loop Vector Avg (2) : " + ((getTimer() - sTime)));
sTime = getTimer();
loopArray(array);
trace("Loop Array Avg (3) : " + ((getTimer() - sTime)));
sTime = getTimer();
loopVector(vector);
trace("Loop Vector Avg (3) : " + ((getTimer() - sTime)));
}
private function loopArray(a:Array, isRead:Boolean = true):void
{
var len:Number = a.length;
var n:int;
for (var i:int = 0; i < NUM_LOOPS; i++)
{
for (var k:int = 0; k < len; k++)
{
if (isRead)
n = a[k];
else
a[k] = 100;
}
}
}
private function loopVector(v:Vector.<int>, isRead:Boolean = true):void
{
var len:Number = v.length;
var n:int;
for (var i:int = 0; i < NUM_LOOPS; i++)
{
for (var k:int = 0; k < len; k++)
{
if (isRead)
n = v[k];
else
v[k] = 100;
}
}
}
上面的测试代码,大致输出如下:
Loop Array Avg (1) : 3074
Loop Vector Avg (1) : 1749
Loop Array Avg (2) : 1835
Loop Vector Avg (2) : 1635
Loop Array Avg (3) : 1675
Loop Vector Avg (3) : 1649
但如果把Loop Array Avg (1) Loop Vector Avg (1) 注释掉,结果会输出如下:
Loop Array Avg (2) : 1881
Loop Vector Avg (2) : 1641
Loop Array Avg (3) : 1794
Loop Vector Avg (3) : 1704
可见,array只是慢在写操作上(因为要自动扩容),如果写操作不除非自动扩容时,写操作的速度和vector其实是差不多的。
至于读操作,array和vector其实是差不多的