The Magic Behind Interface

AS3 Vector vs Array Speed Test

You’ve probably heard that the Vector class in Flash Player 10 is much faster than using the Array class. But how much faster? Well, its a lot faster…about 8x faster in this case. Here’s the results of a speed test, I put 1,677,751 random numbers into either an Array or Vector, then looped back through them to get a total sum.

Vector – uncasted loop
— 27ms —

Vector – casted loop
— 91ms —

Array – casted loop
— 111ms —

Array – uncasted loop
— 232ms —

Here’s what I mean by a “casted” or “uncasted” loop.

for(i = 1677751; i > -1; i--) {
//_sum += _numArray[i];          // UNCASTED - with Vector Objects this is faster, but its slower with Array Objects
_sum += Number(_numArray[i]);    // CASTED - with Array Objects this is faster, but its slower with Vector Objects
}
*Notice that casting Array elements is about twice as fast as uncasted Array elements, but casting Vector elements actually slows the loop down.

So casting an Array element is simply wrapping it in it’s data type. So in the above example, I’m using an Array of Number objects, and only Number objects. Therefore, when looping through the Array you can speed it up by essentially telling the compiler that everything in that Array is a Number. When you’re working with Vector Objects however, casting is automatic, and manually casting elements actually slows the loop down.

So moral of the story:

  • Use Vectors if you can, they’re way faster
  • if you’re using Arrays, only use one data type per Array and cast them when looping
  • if you’re using Vectors, no need to cast them when looping

Download the example here, you’ll need Flash CS 4.

Related Links:

ActioScript 3 Vector / Array Performance Comparison

Strongly Typed Arrays

Leave a Reply