Creating and configuring Sprite
and TextField
objects at runtime can be costly if you are creating hundreds of thousands of these on a single frame. Therefore a common trick is "pooling" these objects for later reuse. Remember we are not just trying to optimize the creation time (new Sprite()
) but also the configuration (setting of default properties).
Lets say we were building a list component using hundreds of TextField objects. When you need to create a new object, check if an existing object can be reused.
var pool:Array = [];
if (pool.length > 0){
// reuse an existing TextField
var label = pool.pop();
}else{
// create a new TextField
label = new TextField();
// initialize your TextField over here
label.setDefaultTextFormat(...);
label.multiline = false;
label.selectable = false;
}
// add the TextField into the holder so it appears on-screen
// you will need to layout it and set its "text" and other stuff seperately
holder.addChild(label);
Later, when you are destroying your component (or removing it from screen), remember to add unused labels back into the pool.
foreach (var label in allLabels){
label.parent.removeChild(label); // remove from parent Sprite
pool.push(label); // add to pool
}
In most cases it is best to create a pool per usage instead of a global pool. Disadvantages to a creating a global pool is you need to re-initialize the object everytime to retrieve it from the pool, to negate the settings done by other functions. This is equally costly and pretty much negates the performance boost of using pooling in the first place.