Reputation: 387607
Suppose I have a class structure like the following, where I have a temporary child that is displayed and later replaced and as such no longer needed. However as multiple methods access that child before, I need it to be a class variable.
So after replacing that child, I no longer need it and want to allow the garbage collection to reuse that space. As the variable is a class variable, I cannot use delete tempChild
. Normally the garbage collection will free the memory when there are no more references to it; so my question is if simply assigning null
to that variable is enough to activate the GC for it.
class Test extends Sprite
{
private var tempChild:Sprite;
public function Test ()
{
tempChild = new Sprite();
tempChild.graphics.drawRect( 0, 0, 100, 100 );
this.addChild( tempChild );
}
public function replace ( obj:DisplayObject ):void
{
this.removeChild( tempChild );
tempChild = null; // <-- here I want to free the variable
this.addChild( obj );
}
}
edit: Just did a quick benchmark for this, results are below:
Test type A: Storing the Sprite reference as a private class variable
Test type B: Accessing it via child index (getChildAt
)
As I only remove the element once, but have to access it multiple times, I'll stick to option A (which is basically like the code above).
Upvotes: 0
Views: 252
Reputation: 45324
Your code doesn't show a reason to hold onto "tempChild" in the first place. Assuming you do need it, then, yes, assigning null to tempChild will allow the object that tempChild referred to to be GCed (as long as no other references to it exist). But why have "tempChild" when you could simply refer to this
's first child?
Upvotes: 1