O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Disposing of Objects Intentionally

In ActionScript, there is no direct way to remove an object from system memory. All object-removal happens indirectly, through the automatic garbage collection system.

However, while a program cannot remove an object from system memory, it can at least make an object eligible for removal by eliminating all program references to it. To eliminate all references to an object, we must manually remove it from any arrays that contain it and assign null (or some other value) to any variable that references it.

Making an object eligible for garbage collection does not immediately remove that object from memory. It simply gives ActionScript authorization to remove the object when and if a garbage collection cycle occurs.

Note, however, that creating and then removing objects from memory is often less efficient than reusing objects.

Tip

Wherever possible, you should strive to reuse objects rather than dispose them.

Returning, once again, to the virtual zoo program, consider the following code. It feeds a pet five apples.

package {
  import flash.display.Sprite;
  import zoo.*;

  public class VirtualZoo extends Sprite {
    private var pet:VirtualPet;

    public function VirtualZoo () {
      pet = new VirtualPet("Stan");
      pet.eat(new Apple());
      pet.eat(new Apple());
      pet.eat(new Apple());
      pet.eat(new Apple());
      pet.eat(new Apple());
    }
  }
}

Notice that each time the preceding code feeds the pet, it creates a new Apple instance and passes that instance to the eat( ) method. Each time ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required