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...
MyCustomObject(container.getChildAt(i)).mySpecialFunction();

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;
tempItem.mySpecialFunction();

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?

Answers


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: http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html


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 flash.net.URLRequest.
    trace(e); 
}

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.


Need Your Help

Use Perl to count occurrences of all words in a file or in all files in a directory

regex perl perlscript

So I am trying to write a Perl script which will take in 3 arguments.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.