When the client has finished, it returns the object to the pool rather than destroying it; this can be done manually or automatically.
If a previously prepared object is available, it is returned immediately, avoiding the instantiation cost.
When the object has been used and is no longer needed, it is returned to the pool, allowing it to be used again in the future without repeating the computationally expensive instantiation process.
If this number is reached and a new item is requested, an exception may be thrown, or the thread will be blocked until an object is released back into the pool.
The object pool design pattern is used in several places in the standard classes of the .NET Framework.
Object pooling can offer a significant performance boost in situations where the cost of initializing a class instance is high and the rate of instantiation and destruction of a class is high – in this case objects can frequently be reused, and each reuse saves a significant amount of time.
In other situations, simple object pooling (that hold no external resources, but only occupy memory) may not be efficient and could decrease performance.
Object pools can be implemented in an automated fashion in languages like C++ via smart pointers.
Opponents usually say that object allocation is relatively fast in modern languages with garbage collectors; while the operator new needs only ten instructions, the classic new - delete pair found in pooling designs requires hundreds of them as it does more complex work.
In contrast, keeping a large number of "live" but unused objects increases the duration of garbage collection.
[1] The following Go code initializes a resource pool of a specified size (concurrent initialization) to avoid resource race issues through channels, and in the case of an empty pool, sets timeout processing to prevent clients from waiting too long.
The following shows the basic code of the object pool design pattern implemented using C#.
Shown is the clean-up process, on release of an object, ensuring it is in a valid state before it can be requested from the pool again.