Search code examples
actionscript-3flashmemory-managementflash-cs6

Are parameters stored as local variables?


Pretty simple question here: are parameters treated as local variables, in terms of memory allocation?

For example take these two functions:

function foo(parameter:Number):void
    {
        trace("Parameter =", parameter);
    }

    function bar():void
    {
        var x:Number;
        trace("x is a number", x is Number);
    }

Does ActionScript handle both parameter and x in the same way? Are they both created as local variables each time the function is run, and will remain in existence until GC gets rid of them, or are parameters treated differently?


Solution

  • Does ActionScript handle both parameter and x in the same way? Are they both created as local variables each time the function is run, and will remain in existence until GC gets rid of them, or are parameters treated differently?

    The runtime handles parameters a little differently than local variables, but in the end they are both local scope and cleaned up when the function returns. For all intents and purposes a parameter is a local variable.

    What's important to understand is how arguments passed to functions work in AS3.

    In ActionScript 3.0, all arguments are passed by reference, because all values are stored as objects. However, objects that belong to the primitive data types, which includes Boolean, Number, int, uint, and String, have special operators that make them behave as if they were passed by value.

    All other objects—that is, objects that do not belong to the primitive data types—are always passed by reference, which gives you ability to change the value of the original variable.

    In other words:

    function test(primitive:int, complex:Array):void {
        primitive = 1;
        complex.push("foo");
    }
    
    var i:int = 0;
    var a:Array = [];
    test(i, a);
    trace(i); // 0
    trace(a); // ["hi"]