The object pool behavioral pattern allows you to reuse objects instead of destroying them and creating them again.

This design pattern helps solve two big problems that applications encounter with managing memory especially over a long period of time.

  1. Sometimes objects just take a long time or are otherwise expensive to create. Even if your objects are small and quick, you might sometimes need a lot of them.
  2. As you use and then free memory, a normal memory manager will build up sections of memory that while available are too small to use for large objects because there are other objects sitting in the middle or between free sections.

With this pattern, you allocate a block of memory when your application starts and use that memory to allocate objects that you don’t delete. Instead of deleting them, you mark them with a flag when they are not being used by some other code and are available. Then you manage this collection of objects yourself. this becomes your pool of objects.

Anytime some code needs one of these objects, instead of allocating a new block of memory for that one object, you find an available object that already exists in the pool, mark the object as no longer available, initialize it as if it was just created, and give it to the calling code. When the other code is done with the object, instead of deleting it, it gets returned back to the pool. This just means that the object becomes available again.


What's on your mind?
On a scale of 0 to 10, how likely are you to refer us to friends?