Object pooling is a design pattern wherein a pool of pre-instantiated objects is kept ready in-memory. The objects from this pool are used as & when required. Usage of an object pool reduces the time & resources required to allocate & destroy objects.
While this post talks about an object pool implementation for Unity, the concepts can be generalized & used for any language/framework.
This implementation uses one Stack to store the pool of objects.
- Instantiate n objects, where n is the pool size.
- Set the value of isPooled flag on all objects to true.
- Push objects onto the stack.
- Pop the topmost element in stack. However, if the stack is empty & the pool can be resized, create a new element.
- Set the value of isPooled flag to false.
- Return this object to caller.
Returning an object to pool
- Check if the object is already in pool by testing against the value of isPooled flag.
- If isPooled is false, set the value of isPooled flag to true.
- Push the object onto the stack.
Time Complexity of the algorithm
Since object insertion & retrieval on a stack can be accomplished in O(1), the above mentioned algorithm will have a time complexity of O(1).
Pros & Cons
Since the object retrieved from the pool is not referenced by any data structure, it is disassociated from the pool & can be destroyed if required. Although such an action will defeat the purpose of having a pool, it might prove to be useful in certain situations.
I’d love to hear your comments on this post/ my implementation.