Nov
4

Array Constructors in AS3 Paul

Actionscript, Flash

Arrays in as3 are unique among the other built in types because their constructor behaves differently depending on the number and type of arguments passed in. Passing in multiple arguments allows you to initialize the array with the supplied values. However, passing in a single integer value to the constructor specifies the number of elements in the array.

Honestly, I haven’t figured out why this second way of initializing arrays exists in as3. In languages where memory can be statically allocated , occasionally it is appropriate to create arrays in this fashion. Static allocation can speed up data access and reduce file size because memory can be set-aside in contiguous blocks when your program initializes. However, since memory for arrays in AS3 is dynamically allocated this parameter doesn’t make much sense. If you create an array and initialize it with a size of 5, it still remains a dynamic array and can grow or shrink in size, so you miss out on the benefits of a statically allocated array anyway.

This behaviour can be extremely confusing if you want to initialize with one integer value in the array. For example:

var arr : Array = new Array(5);
trace("Array contents:", arr);
// I expect [5] but actually its five empty elements: [,,,,,]

Initializing an array like this can also cause problems if you’re not paying attention when you populate your array with real content. If you try to push an element in to the array, it is added to the end of the stack, increasing the array’s size.

var arr : Array = new Array(5);
arr.push("foo");
trace("Array length:", arr.length); // 6 
trace("Array contents:", arr); // [,,,,,,”foo”]

If you try to initialize the array with a single decimal number, you get the following error: RangeError: Error #1005: Array index is not a positive integer (3.14)

The interpreter presumptively assumes you were trying to create a new array with 3.14 empty elements in it, instead of a new array with 3.14 as the first and only element.

Of course, there is an easy solution to all this confusing constructor business and that’s to avoid using the regular constructor altogether and initialize arrays using literal syntax.

var foo : Array = [1,2,3]; // Literal Syntax: simple, quick and painless
var bar : Array = new Array(1,2,3); // Standard Array constructor: long and dangerous

It is far too easy for code to be changed in the future so that new Array(1,2,3) becomes new Array(1). With literal syntax you never run the risk of changing the behaviour of your initialization just because you changed the number or type of parameters you were passing in.

This entry was posted on Wednesday, November 4th, 2009 at 4:22 pm and is filed under Actionscript, Flash. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.