Tag Archives: removeChildAt

Flash Optimization – Object Pooling

Flash optimization is becoming increasing important & with alternative development tools that developers can use. We all have a responsibility to build Flash elements that are efficient as much as they are groundbreaking. As someone who feels responsible for the future of this great application, I am creating a Flash Optimization series that will help educate the Flash development community on how to keep their Flash elements as lean as possible.

Another important optimization is called object pooling, which involves reusing objects over time.

You create a defined number of objects during the initialization of your application and store them inside a pool, such as an Array or Vector object. Once you are done with an object, you deactivate it so that it does not consume CPU resources, and
you remove all mutual references
.

However, you DO NOT set the references to null, which would make it eligible for garbage collection. You just put the object back into the pool, and retrieve it when you need a new object. Reusing objects reduces the need to instantiate objects, which can be expensive. It also reduces the chances of the garbage collector running, which can slow down your application. The following code illustrates the object pooling technique:


package
 {
 import flash.display.Sprite;

public final class SpritePool
 {
 private static var MAX_VALUE:uint;
 private static var GROWTH_VALUE:uint;
 private static var counter:uint;
 private static var pool:Vector.<Sprite>;
 private static var currentSprite:Sprite;

public static function initialize( maxPoolSize:uint, growthValue:uint ):void
 {
 MAX_VALUE = maxPoolSize;
 GROWTH_VALUE = growthValue;
 counter = maxPoolSize;

var i:uint = maxPoolSize;

pool = new Vector.<Sprite>(MAX_VALUE);
 while( –i > -1 )
 pool[i] = new Sprite();
 }

public static function getSprite():Sprite
 {
 if ( counter > 0 )
 return currentSprite = pool[--counter];

var i:uint = GROWTH_VALUE;
 while( –i > -1 )

pool.unshift ( new Sprite() );
 counter = GROWTH_VALUE;
 return getSprite();
 }

public static function disposeSprite(disposedSprite:Sprite):void
 {
 pool[counter++] = disposedSprite;
 }
 }
 }

The SpritePool class creates a pool of new objects at the initialization of the application.
The getSprite() method returns instances of these objects, and the disposeSprite() method releases them. The code allows the pool to grow when it has been consumed completely. It’s also possible to create a fixed-size pool where new objects would not be allocated when the pool is exhausted. Try to avoid creating new objects in loops, if possible.

The following code uses the SpritePool class to retrieve new instances:


const MAX_SPRITES:uint = 100;
 const GROWTH_VALUE:uint = MAX_SPRITES >> 1;
 const MAX_NUM:uint = 10;

SpritePool.initialize ( MAX_SPRITES,  GROWTH_VALUE );

var currentSprite:Sprite;
 var container:Sprite = SpritePool.getSprite();

addChild ( container );

for ( var i:int = 0; i< MAX_NUM; i++ )
 {
 for ( var j:int = 0; j< MAX_NUM; j++ )
 {
 currentSprite = SpritePool.getSprite();
 currentSprite.graphics.beginFill ( 0×990000 );
 currentSprite.graphics.drawCircle ( 10, 10, 10 );
 currentSprite.x = j * (currentSprite.width + 5);
 currentSprite.y = i * (currentSprite.width + 5);
 container.addChild ( currentSprite );
 }
 }

The following code removes all the display objects from the display list when the mouse is clicked, and reuses them
later for another task:


stage.addEventListener ( MouseEvent.CLICK, removeDots );

function removeDots ( e:MouseEvent ):void
 {
 while (container.numChildren > 0 )
 SpritePool.disposeSprite (container.removeChildAt(0) as Sprite );
 }

Note: The pool vector always references the Sprite objects. If you want to remove the object from memory completely, you
would need a dispose() method on the SpritePool class, which would remove all remaining references.

The Display List in AS3

The display list is the system by which objects are displayed on the screen using ActionScript 3.0. It is one of the main concepts to learn if you want to create anything visual using ActionScript. This tutorial will explain the basics concepts involved with the display list and will explore the display list API.

What is the Display List?

The display list is a list that contains all visible Flash content, it is used to control what can appear visually on the screen on the depths at which objects are placed over each other.

Basic Usage of the Display List

The basic usage of the display list involves displaying objects on the screen and removing others from the screen. These two tasks require using the .addChild() and .removeChild() methods.

In order to display an object on the screen you need to use the .addChild() method. Here is a simple example of it:

var myText:TextField = new TextField();
myText.text = “Hello!”;
addChild(myText);

On the other hand, in order to remove an object from the screen you need to use the .removeChild() method. To remove any object from the main timeline you simply remove it this way:

removeChild(myObject);

Hierarchy in the Display List

Objects shown on the display list are placed in a hierarchy. If you add more than one object to the display list using the .addChild() method you will notice that objects you add later will be placed over previous objects (practically covering them).

For example, if you add to the display list an instance of a rectangle class, an instance of a circle class, and finally an instance of a star class using a code similar to the one below, your objects will be placed over each other.

var myTriangle:TriangleShape = new TriangleShape();
var myCircle:CircleShape = new CircleShape();
var myStar:StarShape = new StarShape()

addChild(myTriangle);
addChild(myCircle);
addChild(myStar);

The classes TriangleShape, CircleShape, and StarShape are fictional classes, they do not exist in AS3. However, you may create them yourself by defining them in your library.

The code above will result in your objects getting layered over each other.

AS3 Display List

The logic at which these objects are laid is simple, objects added later to the display list will be placed over objects added earlier.

The position at which an object is played on the display list is called its index. The index at which objects are placed on the list starts from zero, so the first object is placed at position zero, the second at position one, and the third at position two, etc. It is possible to manipulate the position at which your objects are laid over each other by targeting a specific index at which the object is to be placed using the .addChildAt() method.

Using the .addChildAt() Method

Unlike the .addChild() method, the .addChildAt() method requires two parameters, the first is the instance name of the object you wish to add to the list, and the second is the index position you wish to place it at. It is used in the format of generalized code below:

addChildAt(myObject,indexNumber)

For example, say that you want to add the triangle and circle first and then you want to add the star, but you want to make sure that the star object goes behind the triangle and the circle and not above them, you can do that by using the .addChildAt() method.

We will start off by adding the triangle and the circle to the display list, we can do that by using the code below:

var myTriangle:TriangleShape = new TriangleShape();
var myCircle:CircleShape = new CircleShape();
var myStar:StarShape = new StarShape()

addChild(myTriangle);
addChild(myCircle);

The code above will be create the triangle and the circle, the triangle will be at position 0 while the circle will be at position 1.

AS3 Display List - AddChildAt

We want our star to be placed below all of these objects, so we it has to be place at index Zero. We can do that this way:

var myTriangle:TriangleShape = new TriangleShape();
var myCircle:CircleShape = new CircleShape();
var myStar:StarShape = new StarShape()

addChild(myTriangle);
addChild(myCircle);
addChildAt(myStar,0);

This will make our star go behind all the currently existing objects. You should note that this pushes all the other objects 1 index position up to accommodate the star object, so that the triangle is now at index 1 and the circle is now at index 2.

AS3 Display List - AddChildAt

You should note that even though it is possible to place the object at any index position, this position must not exceed the maximum necessary slots for the current number of objects in the list. For example, attempting to place the object at the index position 10 will generate an error because this position goes beyond the scope of the display list. This differs from previous ActionScript versions where it was possible to place objects any any depth regardless of whether that will create a number of empty depths.

Removing Objects Using the removeChildAt() method

In addition to the possibility of adding objects directly by their position, it is also possible to remove objects by referring to their position. If for example you wanted to remove the object at index 1 you can do that by using the code below:

var myTriangle:TriangleShape = new TriangleShape();
var myCircle:CircleShape = new CircleShape();
var myStar:StarShape = new StarShape()

addChild(myTriangle);
addChild(myCircle);
addChild(myStar);

removeChildAt(1);

You should note that this will decrease the index of all objects that were placed in a higher index so that empty index slot is accommodate. This means that the star object is now placed at index position 1 and not index position 2.

Display List - removeChildAt

Swapping Index Positions

In addition to the possibility of positioning your object at a certain index position in the display list by using the .addChildAt(), you can also instantly swap the position with another object by using the .swapChildren() method. This method simply switches the index position of any two objects instantly without affecting any other object in the list.

var myTriangle:TriangleShape = new TriangleShape();
var myCircle:CircleShape = new CircleShape();
var myStar:StarShape = new StarShape()

addChild(myTriangle);
addChild(myCircle);
addChild(myStar);

swapChildren(myStar, myCircle);

The order in which these two objects are passed to the method does not matter. They will all generate the same result:

AS3 Display List - SwapChildren()

Other Display List API

In addition to the methods we mentioned earlier, there are a number of other methods and properties which can be used to retrieve info about currently displayed objects. These methods are self-explanatory:

  1. .getChildIndex(objectName) – This method is used to retrieve the index position of a displayed object by referring to it by its instance name.
  2. .getChildAt(indexPosition) – This method is used to retrieve the instance name of an object by referring to its index position.
  3. .numChildren – This is a property that can be accessed through any display object container to retrieve the number of objects currently found on its display list.

Display Objects and Display Object Containers

It is essential to realize that only Display Objects can be added to a display list. These include objects such as MovieClips, Sprites, TextFields, Videos, Bitmaps, etc. You cannot add non-visual objects to the display list, for example, you cannot add a number variable to the display list.

On the other hand, there are some Display Objects which are also Display Object Containers, these are objects which have their own display list to which other objects could be added. Examples of Display Object Containers include MovieClips and Sprites.

In the example below, a two text field instances will be added to a MovieClip instance, but they will not actually appear on the screen except when their MovieClip container is added to the display list of the main timeline:

var container_mc:MovieClip = new MovieClip();
var text1_txt:TextField = new TextField();
var text2_txt:TextField = new TextField();

container_mc.addChild(text1_txt);
container_mc.addChild(text2_txt);

text1_txt.text = “This text field will not appear on the screen”;
text2_txt.text = “Except if we add its container to the main timeline display list”;

addChild(container_mc);

This was an introduction to the basic role of the display list feature of ActionScript.

Tutorial by Republic of Code