The default memory allocator is not efficient when it comes to frequent
delete operations. There are a number of general purpose allocators that replace the standard one. There are certain situations when you want to improve performance at the cost of using more memory. This is especially true for small objects that are frequently created and destroyed in processing intensive applications. So, I decided to create a class that pools instances of classes, so that
delete works on an array of already existing objects.
To enable pooling for a class, you publically inherit from this class, as shown below:
class myclasstobepooled : public ObjectPool< myclasstobepooled >
Call this function before any objects are created:
Call this function after all objects are deleted:
ObjectPool class maintains a static vector of the pointers of the template type. The overridden
delete operators manage the list.
There is an option to enable or disable thread safety. This is provided so that the critical section calls can be excluded, if the class is used in a single threaded environment, or if the
delete operations are always performed from the same thread.
You can disable multithreading support by commenting the line:
The constructor and destructor gets called even when the placement
delete is used. So, there is no special code required to call the constructor and destructor.
Initially I was thinking about allocating the memory using
malloc and calling the constructor and destructor manually. But, this would be along the lines of a general purpose memory allocator, where the global
delete are overridden.
Suppose you have a class
myclass* p = malloc(sizeof(myclass));
new (p) myclass();
If you have a class that you
delete frequently in a performance critical part of the code, you can get substantial benefits by using this class.
A non-STL version version of the class is available in the downloads section. This was provided by Christian Kaiser.