Using Vectors in ActionScript 3 and Flash Player 10
One of the new ActionScript features included in the Flash Player 10 Public Beta is the inclusion of a Vector class. Essentially, the Vector class is a typed Array, and in addition to ensuring your collection is type safe, can also provide (sometimes significant) performance improvements over using an Array.
Using the Vector class is pretty simple, and very similar to using an Array. In fact, the Vector class contains all of the same methods as the Array class. The main difference is how you instantiate it.
For example, here is how you instantiate an Array:
var a:Array = new Array();
//or
var b:Array = [];
Here is an example of instantiating a Vector that contains int types:
//var VARIABLENAME:Vector.<VECTORTYPE> = new Vector.<VECTORTYPE>();
var vector:Vector.<int> = new Vector.<int>();
Just as in an Array, you can initialize the Vector length to a specific size, by passing the length into the constructor:
var size:int = 7;
var vector:Vector.<int> = new Vector.<int>(size);
However, the Vector has an additional constructor argument, which is a Boolean value that specifies whether the Vector size is fixed (true) or can be changed (false). The default value is false, and the property can be changed with the fixed property:
var size:int = 7;
var fixed:Boolean = true
var vector:Vector.<int> = new Vector.<int>(size, fixed);
vector.fixed = !fixed;
Keep in mind, that if fixed is set to true, then you cannot call any Vector methods that change the length, such as pop(), push(), shift(), etc…
Vectors are also type safe, so while with an Array you can store multiple types:
var s:String = "I am a string";
var d:Date = new Date();
var n:Number = 1138
var a:Array = new Array();
a[0] = s;
a[1] = d;
a[2] = n;
trace(a[1] is Date); //true
You will get a compile time TypeError with a Vector:
var s:String = "I am a string";
var d:Date = new Date();
var n:Number = 1138
var v:Vector.<String> = new Vector.<String>;
v[0] = s;
v[1] = d;
v[2] = n;
trace(v[1] is Date); //false
//Compile time errors:
//Implicit coercion of a value of type Date to an unrelated type String.
//Implicit coercion of a value of type Number to an unrelated type String.
Other than that, working with a Vector is pretty much the same as working with an Array. The APIs are the same, and you can access items directly via their index.
var vector:Vector.<int> = new Vector.<int>();
var rand:Number;
for(var i:int = 0; i < 1000000; i++)
{
rand = (Math.floor(Math.random() * 1000000) as int);
vector.push(rand);
}
trace(vector[7]);
One last thing to keep in mind is that a Vector is basically a dense array. This means that all items in the Vector must have either a value or null.
For example, with an Array, you can do this:
var a:Array = new Array();
a[0] = "foo";
a[6] = "bar";
But if you try that with a Vector:
var v:Vector.<String> = new Vector.<String>();
v[0] = "foo";
v[6] = "bar";
You will get a RangeError at runtime.
The fix is to initialize the Vector length:
var v:Vector.<String> = new Vector.<String>(7);
v[0] = "foo";
v[6] = "bar";
Below is an example that shows a difference in performance in looping over a million numbers in a collection. Keep in mind that this is one specific test, and depending on your use case, performance improvements may be greater or smaller.
package
{
import flash.display.Sprite;
public class VectorTest extends Sprite
{
private static const NUM_LOOPS:int = 5;
public function VectorTest()
{
var vector:Vector.<int> = new Vector.<int>();
var array:Array = new Array();
//populate data
var rand:Number;
for(var i:int = 0; i < 1000000; i++)
{
rand = (Math.floor(Math.random() * 1000000) as int);
vector.push(rand);
array.push(rand);
}
var sTime:Number = getMilliseconds();
loopArray(array);
trace("Loop Array Avg (5) : " + ((getMilliseconds() - sTime)/NUM_LOOPS));
sTime = getMilliseconds();
loopVector(vector);
trace("Loop Vector Avg (5) : " + ((getMilliseconds() - sTime)/NUM_LOOPS));
}
private function getMilliseconds():Number
{
return (new Date()).getTime();
}
private function loopArray(a:Array):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++)
{
n = a[k];
}
}
}
private function loopVector(v:Vector.<int>):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++)
{
n = v[k];
}
}
}
}
}
On my machine, I get this output:
Loop Array Avg (5) : 115.8
Loop Vector Avg (5) : 108.8
Which is significant given the simplicity of the test (just referencing the value).
You can find more information on Vectors in the Flash Player 10 Beta documentation.
You can find more information on Flash Player 10 on labs.






This is really good, should be better than arrays (memory & cpu).
I`m really happy about actionscript 3 , every day actionscript recieve more power.
those vectors looks like C programming :)
Armando Leopoldo Keller
19 Aug 08 at 4:39 pm
Glad AS3 is getting more data structures (but not too much bloat unless it helps speed up performance like this). Vectors are nice, the syntax with the. syntax like generics is a bit odd but probably due to the compiler parser so it seems fair. Polygonal has some great game data structures that might be nice to have native as well. Great stuff lately.
Ryan Christensen
19 Aug 08 at 6:46 pm
Well, why is it that I can’t download the Doc (zip) file? Mike, please double check if the link is properly linked and available.
Brajeshwar
19 Aug 08 at 10:32 pm
@Brajeshwar
Should be fixed now.
Thanks for heads up and sorry about the hassle.
mike chambers
mesh@adobe.com
mikechambers
19 Aug 08 at 10:36 pm
It’s great to see stuff like this making its way into the player, but it would be nice if there was an equivalent Matrix class (not the transformation matrix – a real n-dimensional matrix). For the CleVR Stitcher we needed to implement classes for matrix algebra (available in our open source library at http://clevrlib.riaforge.org/), and type safety would have been useful. Support for using math operators on vectors and matrices would be best of all.
Matt Kane
19 Aug 08 at 11:12 pm
@Matt
Have you looked at PixelBender for implimenting some of your math and graphics code?
From:
http://www.adobe.com/devnet/logged_in/jchurch_flashplayer10.html
–
In addition to image filters and effects, Pixel Bender can be used to process other types of information. With new capabilities in sound, you can write live audio filters or just use the power of Pixel Bender’s number crunching engine to process data asynchronously in a separate thread.
–
You wont get the type safety, but you could potentially get huge performance increases.
More info on PixelBender here:
http://labs.adobe.com/wiki/index.php/Pixel_Bender_Toolkit
mike chambers
mesh@adobe.com
mikechambers
19 Aug 08 at 11:15 pm
Hi Mike, thanks a lot for this insight…
A question though: will some of the Flex classes be updated to support generics.. ? The biggest one that comes to my mind is ArrayCollection ; will there be a VectorCollection?
{Maz}
Maz
19 Aug 08 at 11:52 pm
Yeah, I’ve had a look at it and it does look really useful. I think we’ll almost certainly end up using it for the next version of the viewer which should hopefully make full-screen panoramas a lot smoother to display. The viewer code is not massively complicated (just a reprojection) and we currently implement it as a DisplacementMapFilter which is a seriously hacky way of doing it. It also restricts us to 8 bits per pixel of displacement, which leads to banding when displaying images with very high fields of view.
The Stitcher is less of a no-brainer, as it would involve porting a massive amount of very complicated code. As you can imagine, stitching images involves some pretty hardcore calculations, so I’d not be looking forward to first learning a new language and then porting tens of thousands of lines of code! And I’m the only coder in the company. But it’s certainly something I’ll be keeping an eye on, and will perhaps port parts of it over if it seems appropriate. We’re always looking for ways of squeezing more performance out of the AIR runtime.
Matt Kane
19 Aug 08 at 11:59 pm
Just curious regarding the derivation of the name “Vector”.
I usually have understood a vector to be a representation of direction. So just trying to understand the selection of the term Vector.
As I would have expected such to be a graphical element and not something akin to an array.
Just trying to gain insight.
:)
Jason The Saj
20 Aug 08 at 4:58 am
[...] Read more [...]
Tutorials on Flash Player 10 Roundup part 1 | Lemlinh.com
20 Aug 08 at 7:41 am
@jason: A vector is, roughly, another name for a one-dimensional matrix. The word is often used synonymously with array. A spatial vector, which is the kind you know, represents direction and magnitude (distance or speed). Roughly “how to get to one place from another”. These can be represented using the vectors as described here.
The matrix algebra stuff that I was referring to can then be used to perform operations on those vectors, such as adding them (which would give the result of moving the distance and direction of one vector then the other). This sort of stuff is very useful for lots of things like image processing, but support for it in Actionscript is limited. My library provides some of that missing functionality, as does this new class.
Hope that makes sense!
Matt
Matt Kane
20 Aug 08 at 8:04 am
I want it yesterday :)
I have the same question about collections as Maz.
Thanks for the sample.
Garth Braithwaite
20 Aug 08 at 1:59 pm
Hey Mike,
Do you know if developers will be able to define their own generics? (new MyCollection.())
… or is the generic syntax of Vector a special case, defined internally only.
Thanks.
Peter Wong
20 Aug 08 at 11:34 pm
[...] infos here: Using Vectors in ActionScript 3 and Flash Player 10 No Comments, Comment or [...]
blog.betabong.com - Flash Player 10 – I love speed
22 Aug 08 at 1:35 am
I am an Adobe employee. I write a library in ActionScript these days as a developer.
One thing I would appreciate flex team could help with is making it easy to transition away from Arrays to Vector. I know I wish to do this, but if a ready-made ’sed’ script could help me save some time doing this transition – I would appreciate it.
aditya kumar pandey
30 Aug 08 at 11:00 pm
[...] (Mike Chambers), ???????? ??????? ?? ??????? ???? ??? ?????? «Using Vectors in ActionScript 3 and Flash Player 10». ?????????? ????????????? ???? ?? ????? [...]
????????????? ?????? Vector ? ActionScript 3 ? Flash Player 10 beta — Garbage Collector
9 Sep 08 at 3:06 pm
[...] my original post on the new Flash Player 10 Vector class, I did a simple example that showed Vectors being slightly faster than Array when just populating [...]
ActioScript 3 Vector / Array Performance Comparison at Mike Chambers
24 Sep 08 at 4:48 pm
[...] require user prompts), the previously mentioned unloadAndStop() method will be added and the new Vector datatype for strongly typed [...]
Flash on the Beach 2008 - Tuesday Write Up - JonnyReeves.co.uk
1 Oct 08 at 3:34 am
[...] mike chambers – using the new Vector class [...]
Flash Player 10 New Features | experimo
6 Oct 08 at 4:00 pm
[...] 10 is great news. There are so many things in it from a new data structure (Vector), to local FileReference, to Matrix and 3D helpers, to speed improvements and video enhancements [...]
Flash 10 Officially Released « [ draw.logic ]
15 Oct 08 at 7:07 am
I am so happy to finally have the vector type available. Next… Method overloading!
Philip
10 Nov 08 at 9:24 pm
My 3D engine got 50% SLOWER when I switched to vectors from arrays… IT DOESN’T MAKE ANY SENSE!!!
Daniel
13 Dec 08 at 7:39 am
@Mike
Do we really need only this class (I mean vector class)?
This is nice effort by flex team and its appreciable. B U T….motto of my question is if AS3 has vector class, why not all classes of its families (like map, hashmap, queue, stack and others).
Also whats the significance of Vector class(over favorite Array and Object class) which forced flex team to add it into standard AS3 library?
DELL
22 Mar 09 at 11:53 pm
[...] relies mostly on a linked list implementation to iterate over the particles, and using the Flash 10 Vector type to allow for faster access to write to screen. Another speed improvement over the Alchemy version [...]
More play with Alchemy : Lookup table effects. | UnitZeroOne
6 Apr 09 at 2:11 am
It’s also possible to initialize a Vector using a source array, by using the Vector function: http://www.daveoncode.com/2009/04/06/actionscript-vector-class-initialization-with-a-source-array/
DaveOnCode
6 Apr 09 at 8:39 am
[...] Mike Chambers: Using Vectors in ActionScript 3 and Flash Player 10 [...]
Targetting Flash Player 10 on Flex development « :maohao:
4 May 09 at 7:46 pm
[...] relies mostly on a linked list implementation to iterate over the particles, and using the Flash 10 Vector type to allow for faster access to write to screen. Another speed improvement over the Alchemy version [...]
More play with Alchemy : Lookup table effects. - unitzeroone(beta)
7 May 09 at 8:25 am
[...] comment on Mike Chamer’s post on Vectors in AS3 got me thinking .. how hard would it be implement a VectorCollection in AS3? I [...]
josh >> /dev/blog & » Blog Archive » VectorCollection
13 May 09 at 9:12 pm
[...] relacionado: Documentação do Vector Teste de performance Post sobre Vector por: Mike Chambers Post sobre Vector por: DaveOnCode Post sobre Vector por: The Back Button Posts relacionados:JPEG [...]
Usando Vector em AS3 para Flash Player 10 | Bruno Soares
25 May 09 at 7:21 pm
Great stuff!!! It’s like C# generics!! List l = new List();
anders
30 Jun 09 at 1:41 am
[...] require user prompts), the previously mentioned unloadAndStop() method will be added and the new Vector datatype for strongly typed [...]
Mind Candy » Blog Archive » Flash on the Beach 2008
17 Nov 09 at 3:30 am
Hi Mike,
How to convert Vector Collection to ArrayCollection.
Manikandan
17 Nov 09 at 11:29 pm
Hi,
i need to crop or mask the particular part an image in actionscript 3.0 like working to free-form select tool in mspaint. what can i do? anybody help me?
ramja
20 Jan 10 at 12:01 am
Top Ten of Missing Features in Adobe Flex…
As a Java developer, who worked for more than a year with Flex I suffered from a couple of pain points – features that I am missing badly in Action Script 3.0. Here is my personal list of things that I wish Adobe would incorporate into Action Script 4….
Occasional Thoughts
25 Jan 10 at 3:22 pm
Hi ,
I learn a lot about Vector from your tutorial but I do want to ask you one question
var vect:Vector. = new Vector.(3);
//let say I have MovieClip named mc1,mc2 and mc3
//if i do this
vect.push(mc1,mc2,mc3);
trace(vect)
//it will give null,null,null,[object MovieClip],[object MovieClip],[object MovieClip]
What I am trying to ask is all we have to use is
vect[0] =mc1 and so on
Santosh
18 Feb 10 at 11:06 pm
[...] Vectors in Actionscript: Mike Chambers Article -> The new Vector class is simply a typed ‘Array’ with huge performance benefits (Kick ass [...]
Flex 4 Optimize those Item Renderers | Tyrone Neill
5 Mar 10 at 3:39 pm