Object Pool The Problem Solution How it works?

Object Pool


The Problem:

Lets say we're programming a game and whenever the hero casts a spell, a blast effect is created.

The particles in special effects are often implemented as objects each with a different set of positional data , velocity, etc, and are often short lived. The act of creating these particles are often slow since the machine has to instantiate (allocate space in memory, create all the attributes & etc) each particles. Once they disappear, the program has to delete them from memory. This is easy to manage when there are few objects, but with thousands of particles being created and subsequently destroyed every time the player casts a spell can lead to memory fragmentation & memory leaks when implemented incorrectly.


Memory Fragmentation

Memory fragmentation is a condition where the sum of all usable memory in your system is large enough to satisfy a memory allocation request, but the size of any contigous fragment in memory is too small to store the given data. Lets take a look at the diagram below.

Memory Leaks

Memory Leaks happens when some data has been allocated in memory but is "forgotten" or the reference to the data is lost, so the data cannot to deallocated from memory.

When your program continously create theses forgotten blocks of data, your computer will eventually run out of free memory, causing the computer to crash.

The Solution:

The object pool pattern propose that we allocate more many than enough desired objects at the start of the program, and design a system to manage the objects that are in use, and objects that are not in use. When an object in use is no longer required, it'll be placed back into the "not in use" section and when more objects are require, we'll simply grab the required amount from the "not in use" section. Doing things this way removes the need to delete and create objects, thus eliminating any chance of memory mismanagement. The object pool can also be designed to grow or shrink when needed.

Key characteristic:

How does it work?