Basic Vector Performance in AS3

24 July 2009

I started working with vectors in ActionScript 3 recently, and wanted to make sure I was using them in the most efficient way. I performed several rudimentary tests of various ways to fill a vector with values. None of the results were very surprising, but it's nice to have numbers to back up my assumptions.

Here’s what I discovered.

Don’t use push(). This is the slowest way I found to fill a vector. First, resizing the vector is going to have an impact on performance. Second, even if you need your vector to expand, push() is not the fastest option. Instead, always specify the index using a counter variable, e.g.  vector[index++] = item;. This can take under 25 percent of the time it takes to push the same items.

Create the vector with enough capacity to hold all your items. If you know your vector will have 100,000 items in it, create a vector with that capacity. This can be twice as fast as growing the vector for every item.

Fixing the size of the vector doesn’t help performance. If you create a vector of a given size, and don’t resize the vector, it makes no difference whether the vector is fixed size or not.

The tests I ran were very basic. For all, I ran a variation of

var vector:Vector.<int> = new Vector.<int>(5000000, true);

for (var i:int = 0; i < 5000000; i++) {
  vector[i] = i;

ten times, and averaged the execution time. Results could be different for smaller vectors.