One aspect related to the performance of an application that is often overlooked is the overhead in the execution of specific tasks. Overhead is influenced by various factors. One of these factors, in the context of OOP (Object-Oriented Programming), is the time it takes to create an object: when we create an object, the process of creation and initialization can be more or less time-consuming depending on the complexity of the object and the initialization process of its attributes. The repeated creation and destruction of this object negatively impact the runtime of both the individual process and the entire application as a whole.
One possible solution to this problem would be to have pre-created objects available, for which we do not have to worry about their lifecycle.
One of the Design Patterns belonging to the category of Creational Design Patterns is the Object Pool. According to its definition:
The Object Pool is a creational design pattern, which is one of those patterns applicable to resolving performance issues related to the initialization process of the components (classes) that make up our system.
The underlying concept of the Object Pool can be summarized by describing a process in which a client, in need of an instance of a class, requests it from the Pool. The Pool, upon the request, 'checks' if it has an instance of that class available to fulfill the request. If the instance is available in the pool, it is returned; if the instance is not available, the Object Pool, which knows the method for creating the instance, creates a new one and returns it.
When the client finishes using the obtained instance, it returns that instance to the Pool, which does not destroy it but makes it available for future requests.
This process is cyclical and, in the best case scenario, helps reduce the overhead derived from creating an instance when it is already present in the pool.
DMVCFramework, the RESTful Framework, JSON-RPC, and ActiveRecord for Delphi maintained by Daniele Teti and the DMVCFramework team, has many small but important features that may be lesser-known. One of these is the implementation of the ObjectPool.
The unit MVCFramework.ObjectPool.pas, present in DMVCFramework, defines a class that implements the Object Pool as the pattern defines it:
TObjectPool<T: class, constructor> = class(TInterfacedObject, IObjectPool<T>)
The (generic) class TObjectPool implements the IObjectPool<T: class, constructor> interface. IObjectPool requires the implementation of two specific methods for pooling:
function GetFromPool(const RaiseExceptionIfNotAvailable: Boolean = False): T;
procedure ReleaseToPool(const Obj: T);
`GetFromPool()` is called to obtain an object from the Pool, and `ReleaseToPool()` is called to release and return the object instance to the Pool.
An instance of the TObjectPool class is obtained by invoking the class function `CreatePool()` of the TPoolFactory class, defined as follows: