views:

37

answers:

2

What gives the best performance? (edited to include another option)

var myVec:Vector.<Number> = new Vector.<Number>();

for (...)
    // Do stuff - example: myVec.push(Math.random());

// Need to empty and repopulate vector
myVec.splice(0, myVec.length);
// OR
myVec = new Vector.<Number>();
// OR 
myVec.length = 0;
A: 

I have heard that:

myVec.length=0

is the fastest way... but i never verify this point

OXMO456
A: 

Using the code below I've found myVec = new Vector.<T>() is the fastest way.

Output (average times in ms to empty a Vector.<Number> with 100000 random entries):

0.679 // using splice()
0.024 // using new Vector.<T>()
0.115 // using .length = 0;

Code:

var myVec:Vector.<Number> = new Vector.<Number>();

var emptyTime:int;
var startTime:int;

var totalEmptyTime:Number = 0;

// Need to empty and repopulate vector
const NUM_TRIALS:int = 1000;

var j:int;
for(j = 0; j < NUM_TRIALS; j++)
{
    fillVector();
    startTime = getTimer();
    myVec.splice(0, myVec.length);
    emptyTime = getTimer() - startTime;
    totalEmptyTime += emptyTime;
}

trace(totalEmptyTime/NUM_TRIALS);
totalEmptyTime = 0;
// OR
for(j = 0; j < NUM_TRIALS; j++)
{
    fillVector();
    startTime = getTimer();
    myVec = new Vector.<Number>();
    emptyTime = getTimer() - startTime;
    totalEmptyTime += emptyTime;
}

trace(totalEmptyTime/NUM_TRIALS);
totalEmptyTime = 0;
// OR 
for(j = 0; j < NUM_TRIALS; j++)
{
    fillVector();
    startTime = getTimer();
    myVec.length = 0;
    emptyTime = getTimer() - startTime;
    totalEmptyTime += emptyTime;
}

trace(totalEmptyTime/NUM_TRIALS);

function fillVector():void
{
    for (var i:int = 0; i < 100000; i++)
        myVec.push(Math.random());
}
Mahir