views:

78

answers:

1

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)

  • Test 1: Accessing the sprite once -> B is about three times as slow as A
  • Test 2: Deleting the sprite (removeChild vs. removeChildAt) -> nearly equal, no visible performance plus from using just the index (and skipping the search for the object)
  • Test 3: Access the sprite multiple times -> A is about 20% faster than B
  • Test 4: Same as 2, but with additional sprites that fill up the childList (so removeChild actually has to search) -> B is about 25% faster than A (as expected)

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).

+1  A: 

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?

Jonathan Feinberg
In the actual code the Sprite holds some more childs other than the `tempChild` and the later added element. Also I guess accessing to the first child multiple times (in different methods) is not as efficient as simply storing it in a class variable.
poke
I added a benchmark on that in my question, if you are interested.
poke