Actionscript - is it better to cast or create a new variable? Or does it matter at all?

I find that in my daily Flex/Flash work, I do this number a lot:

//Calling a function...

The question is - is this the best way to do this? Should I do this:

//Calling a function
var tempItem:MyCustomObject = container.getChildAt(i) as MyCustomObject;

It might be incidental but I'm just wondering if there is an "accepted" way or a preferred way to do this. The second option seems more readable but I wonder if it takes more of a performance hit to create a new variable. Or does it all come down to style and preference?


It generally doesn't matter. Creating a var just creates a pointer to the object, so it's not using more memory or anything like that.

The second example is definitely more readable and debuggable and should thus be preferred.

The risk you run from creating temp vars is that you might delay or prevent garbage collection for that object. This generally isn't a problem when it's just a local var in a function; just keep scope in mind when you're creating vars and passing them around.

For in-depth on the subject, read Grant Skinner's series on resource management in AVM2:

It's important to remember that there is a difference between explicit casting and using the as keyword. Casting throws an error when it fails, whereas the as keyword does not (it just returns null).

// a casting error
try {
    var number:int = 666;
    var urlreq:URLRequest = URLRequest( number );
} catch(e:TypeError) {
    // TypeError: Error #1034: Type Coercion failed: cannot 
    //            convert 666 to

Whereas the as keyword fails silently:

var number:int = 666;
var urlreq:URLRequest = number as URLRequest;
trace(urlreq); // prints null to the debug pane

Personally, I bear these behaviours in mind when deciding method to use. Generally, I'd recommend casting explicitly, as you'll know exactly how/when a cast failed. Often, though, you might want to fail silently and continue.

for the second example you might want to test for the nullity to avoid a NullPointerException when invoking "mySpecialFunction", e.g.

var tempItem:MyCustomObject = container.getChildAt(i) as MyCustomObject;

if ( tempItem )

I usually prefer the second approach but you have to remember that you can only use the as operator for casting "Date" and "Array" types.

Need Your Help

Select the Text of the textbox for copy

wpf uibutton copy-paste

here are the steps which should happen

What is the proper way to update all elements of a rendered page via AJAX?

php ajax comet long-polling

I have a complicated page being rendered by PHP and would like to keep all elements of the page up to date via AJAX long polling. Is there some kind of general / clever way to design an infrastruc...