- Re-using pre-instantiated objects in a pool.
- Destroying then re-instantiating objects in a pool.
Both pools are limited.
When creating loads of objects which is better for performance?
Both pools are limited.
When creating loads of objects which is better for performance?
When you instantiate a new object, a whole bunch of stuff needs to happen:
The engine has to allocate memory to hold its native/unmanaged representation (the guts of the object inside the engine itself)
The .Net runtime has to allocate memory to hold its managed representation (the parts visible to your C# scripts, and any C#-based components), and register them with the garbage collector (GC alloc)
The new objects need to be constructed in that allocated memory.
The deserializer has to copy the data from the prefab you're instantiating into this new memory space, and wire-up any internal references between objects/components in the new copy.
The new object needs to be added into the engine's various update lists for scripting callbacks, physics, rendering, etc.
Components' Awake, OnEnable, and Start methods need to be run.
This takes time. Not a lot individually, but it adds up. When you Destroy an object, all this work needs to be undone, and that takes time too.
The "GC alloc" bit also means you're using up some of your garbage collection headroom. Once you run out, the runtime puts your scripts on hold to do a full mark & sweep pass and clear out any unused objects, and compact the used memory to free up space. This can cause a noticeable hitch in your framerate, so it's best if we don't trigger the garbage collector too frequently in the thick of play.
When you keep objects in a pool, deactivate them instead of destroying them, and re-activate them to recycle them instead of spawning new ones, you get to skip doing almost all of this work, and you create no new work for the garbage collector.
So pooling/recycling is definitely more efficient than instantiating/destroying, for objects that you're spawning & despawning frequently. Don't worry about it for objects you spawn only a handful of times in your level, but things like bullets or particle effects that you use by the dozens or hundreds, that might spawn & despawn every few seconds, are prime candidates for this kind of optimization - especially if you're targeting mobile.