PDA

View Full Version : Storing a local var, what happens in memory?



furyan.be
January 14th, 2009, 07:11 PM
Hi, im trying to get a deeper understanding on how as works, I was wondering:



for(var i:int = 0; i < 100; i++)
{

var s:Sprite = new Sprite();
s.name = "sprite"+i;
addChild(s);
}


var s is a reference to the the new Sprite
new Sprite is stored inside memory at some place
var s is also stored inside memory but only takes a small amount of space because it only needs to point to new Sprite?

the second time the loop runs, will the old var s be overwritten in memory? or will it be asigned to a new position in memory?

would it be beneficial if i typed something like this?


for(var i:int = 0; i < 100; i++)
{

var s:Sprite = new Sprite();
s.name = "sprite"+i;
addChild(s);
s = null
}

Krilnon
January 14th, 2009, 07:24 PM
It would probably just be unnoticeably detrimental to performance.


var s is a reference to the the new Sprite

Not really; s holds a reference to the Sprite.

Another notable thing about the example here is that, in ActionScript, variable declarations apply to the inner-most function or class in which the variable was defined. So, declaring (using the var keyword) s before or after the loop makes no difference other than perhaps a difference in the level of code clarity. You aren't creating a new variable (new space for a Sprite reference, in this case) each time the loop runs. In contrast, function-local variables are created and destroyed at the beginning and end of function execution, respectively.


the second time the loop runs, will the old var s be overwritten in memory? or will it be asigned to a new position in memory?


The old value ofs will be overwritten.

furyan.be
January 15th, 2009, 06:12 AM
aha, thank you for the insight!