- Home /
Pooling object performs the same or worse than instantiate/destroy?
So I recently started pooling and recycling the objects I frequently instantiate, because I've heard multiple times both here and on the forums that it is better for performance. However, when I make a build with an FPS counter, the performance during heavy instantiation sequences is pretty much the same, or sometimes worse, than simply instantiating/destroying. Is this normal, or is the benefit of instantiating going to be more of a long run kind of thing as the garbage heap starts to fill up?
I wrote my object pooling script myself, mostly with inspiration from this example, except in UnityScript and with some minor tweaks: http://snipt.org/ylxo2 I don't really see anything wrong with it, but maybe a fresh set of eyes might see something.
Well, for starters I wouldn't be using Unity's 'Array' class. It's terribly slow.
Oops, I had the wrong link in there to the script I got my inspiration from, I updated it. I used Array because I knew it was for the most part the same performance wise as ArrayList, but I just noticed that script was using generic lists. Do you think that would improve a bit?
Well, I personally can't really help you with UnityScript optimisation. I don't really know much about that. I could help more if it were C#, I know that.
Never use Array or ArrayList, Array is a good 30X slower than built-in arrays, and 10X slower than List (in general). Any reasonably-implemented pooling will always outperform instantiate/destroy. I don't see what the point is of your container object; there's no reason to parent pooled objects to anything.
Thanks Eric... List it is, then. The container is only to organize my scene view hierarchy when I play in the editor, more of an OCD thing.
Answer by PhobicGunner · Dec 22, 2012 at 12:38 AM
The purpose of object pooling is not to instantiate objects faster, since it most certainly will NOT be faster. BUT, what an object pool does is LIMIT MEMORY CONSUMPTION. Think about it this way - normally you Instantiate and Destroy object. When you Instantiate an object, it allocates memory. When you Destroy an object, it will eventually get cleaned up by Garbage Collection. If you have a lot of objects being instantiated and destroyed frequently, it will almost certainly start triggering the GC which can result in frequent hiccups and freezes.
However, in an object pooling system, the object is instantiated, but never actually destroyed. Rather, it is de-activated and then later when another object of the same type needs to be instantiated, instead of instantiating it just re-activates the previous object. In many cases (particularly frequent calls to Instantiate) this can save tons of memory, and in the long run eliminate a lot of garbage collection.