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

I find that in my daily Flex / Flash job, 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();

      

This may be random, but I'm just wondering if there is an "acceptable" way or a preferred way to do this. The second option seems more readable, but I'm wondering if more performance is required to create a new variable. Or is it all about style and preference?

+1


source to share


3 answers


It doesn't matter at all. Creating var just creates a pointer to the object, so it doesn't use more memory or anything.

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



The risk you run when creating temp vars is that you can delay or prevent garbage collection for that object. This is usually not a problem when it is just a local var in a function; just be mindful of when you create vars and pass them.

For an in-depth look at the topic, read Grant Skinner's section on resource management in AVM2: http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html

+2


source


It's important to remember that there is a difference between explicit casting and using a keyword as

. Casting throws an error when it fails, whereas the keyword as

doesn't return (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); 
}

      

While the keyword as

is failing:



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

      

I personally treat these behaviors when choosing a usage method. Generally, I would recommend casting explicitly, as you will know exactly how / when failing. Often times, however, you can lose silently and continue.

+5


source


for the second example, you can test for nullity to avoid NullPointerException when calling mySpecialFunction like

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

if ( tempItem )
{
   tempItem.mySpecialFunction();
}

      

I usually prefer the second approach, but you must remember that you can only use the as operator to select the Date and Array types.

0


source







All Articles