views:

248

answers:

2

I heard that AS boxes and un-boxes values every time arguments are passed into/out of functions.

A. Therefore, would this be faster?

var val = doWork(50,"hello", 2048);

function doWork (param1,param2,param3){
   t.text = param2;
   return param1+param3;
}

B. Or this?

var val:Number = doWork(50,"hello", 2048);

function doWork (param1:Number,param2:String,param3:Number):Number{
   t.text = param2;
   return param1+param3;
}
A: 

You'll always do better performance-wise declaring types than omitting them, so in your case B is the better answer for that reason alone. It's also better by virtue of not using (by implication) Object.

There's not nearly as much information out there on how ActionScript does its boxing and unboxing (compared to the likes of C# and Java), but the AS3 docs do address it a bit (see Data Types):

http://livedocs.adobe.com/flex/3/html/help.html?content=03_Language_and_Syntax_01.html

In general, though, it's best to avoid runtime type checking and use AS3's "primitives" as defined in the docs (Boolean, Number, int, uint, String). Good luck!

Christian Nunciato
I'm afraid that's not the case in AS 2.
Juan Pablo Califano
Ack, my mad -- I missed that pesky "2"! Sorry about that, folks -- my answer does indeed apply to AS3 and AVM2.
Christian Nunciato
+3  A: 

There's no difference at runtime. AS 2 is run by the Actionscript Virtual Machine 1 (AVM1), which doesn't support static typing, so type information is rather a hint for the compiler to help you catch type inconsistencies earlier. But the same code with or without type annotations produces the same bytecode.

AS 3 is run by AVM2, which supports both dynamic and static typing, so declaring types in the code eliminates some runtime lookup, which makes it faster to execute.

Juan Pablo Califano