We all know by now how beneficial Vector is over Array in most cases. Relating to strict data typing, way to an error free code and of course the performance are some benefits of using Vector instead of Array in Action Script 3.0. Below is a small code snippet of working with Multidimensional vector created dynamically.

for (var i:int=0; i<3; i++) {

	this["myVar_"+i] = new Vector.<Vector.<int>>();

	for (var j:int=0; j<3; j++) {

		this["myVar_"+i][j] = new Vector.<int>();

		for (var k:int=0; k<3; k++) {
			this["myVar_"+i][j][k]=k;
		}
	}
}

To explain the code above for people who don’t understand this easily, there are 3 loops and I am creating 2 dimensional Array Vector – Vector[i] and Vector[j].

As you can also notice, I am creating variables dynamically with no predefined name.  I don’t use var myVariable:Vector syntax as I don’t know the names of variables that I need to create and I don’t know how many I need to create. Hence, I use “this” to create dynamic variable of name ["myVar_" + i]. Thus resulting in myVar_0, myVar_1, myVar_2

For the i loop, I define each dynamic Vector variable as new Vector.<Vector.<int>>(); This is because I know I want to create myVar_i as a Vector and each element in this vector will in turn contain a Vector (similar to 2 dimensional array) and later, each Vector inside myVar_i Vector will contain elements of data type int (Integer). So, as you can see in the j loop, I have initiated each element of myVar_i Vector as new Vectors and specified that each element of [i][j] Vector will contain an int type element. Finally in k loop, I populate/push the Vector with an integer data k.

You may view further comparision of Array and Vector performance in Mike Chambers’ blog.


Leave a Reply