May contain nuts.

I promised to write an article for a mate over a year ago now about object pooling. As you can see, I'm a little late ( And with apologies to Michael, I don't mean to be shit, I just am ).

Ok, pooling. To sum it up it's a way of re-using objects. Creating new objects is costly, so rather than killing them off we just store them away until we need them again. Pooling is perfect for things like baddies, bullets, particles etc.

That's straight forward ? Ignore the data:Array and the init, that's just passing the x,y positions to it.So we check baddie1Pool ( In this case its a Vector, an array does the same job ). If there's a baddie object in there we grab it and use it. If not we create a new instance.

Let's go back to the baddie class, when we declare it dead we simply do this,

return "dead";

Back again to our BaddieHandler class ( I've structured this well haven't I ), in our mainloop we have,

//---------------------------------------------------------------------------------------
private function mainloop_normal():void {
var baddie:Baddie;
var cnt:int=0;
for each (baddie in activeBaddies){
if(baddie.mainloop()=="dead"){
activeBaddies.splice(cnt,1);
//We can live with defining vars in a loop, as it should only be needed once per loop
var type:String=baddie["type"];
if(type!="DontPool"){
var functionCall:Function=this["returnToPool_"+type];
functionCall(baddie);
}
}
cnt++;
}
}

So we loop through the active baddies array, running the mainloop for each baddie. If we get returned "dead" as a string we know we've got to put him back in the pool. This is where that identifier from the start of the post comes back into it.

Finally we have a simple method for putting it back into the pool itself, eg

The nice part is the use of identifier and the dynamic function in the mainloop, see how we create this["returnToPool_"+type] and then just call it, no messing around with any conditionals to see which pool we shouldput the object back into.

And that's how simple pooling is. If you want you can pre-populate your pool ( ie create 30 baddies right at the start of the game, so there's no slow down as you slowly fill the pool to its maximum level ), I just find it easier on my brain to create the instances as I go.