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.

Algorithm

This implementation uses one Stack to store the pool of objects.

Pool creation

  • 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.

Object retrieval

  • 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.

Thoughts?

I’d love to hear your comments on this post/ my implementation.

 

Download Easy Object Pool for Unity (Free)

O(1) object pooling system
Spread the word...
Share on Facebook5Tweet about this on TwitterShare on Google+0Share on LinkedIn0Pin on Pinterest0Share on Reddit0Share on Tumblr0Email this to someone

2 thoughts on “O(1) object pooling system

  • April 11, 2015 at 7:21 pm
    Permalink

    It sounds straight forward enough, just wondering why it requires Unity 5.0? 🙂

    • April 13, 2015 at 9:46 am
      Permalink

      Unity 5.0 is min. requirement because I uploaded the asset using v5.0. The code will run fine on v4.x too. Just drop me an email & I’ll send it to you.

Comments are closed.