views:

1198

answers:

3

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?

+1  A: 

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

RickDT
+5  A: 

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.

aaaidan
A: 

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

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.

Sebastien Benmbarek
You can only use the as operator for casting Date and Array types? That's news to me. I'm pretty sure that's not right.I like your null check.
aaaidan