Class ObjectPool<T>
- Namespace
- WitShells.DesignPatterns.Core
A generic Object Pool that recycles instances of T to reduce
heap allocations and GC pressure. Objects are retrieved with Get() and returned
with Release(T) after use.
public class ObjectPool<T> where T : class, new()
Type Parameters
TThe pooled type. Must be a reference type. If no factory is provided it must also have a public parameterless constructor (
new()constraint).
- Inheritance
-
ObjectPool<T>
- Inherited Members
Examples
var pool = new ObjectPool<Bullet>(() => new Bullet(), initialCapacity: 20);
Bullet b = pool.Get(); // reuse or create
pool.Release(b); // return after use
Remarks
Commonly used in Unity to pool GameObjects, particle effects, projectiles, or any frequently instantiated/destroyed object.
Constructors
ObjectPool(Func<T>, int)
Creates a new pool.
public ObjectPool(Func<T> factoryMethod = null, int initialCapacity = 0)
Parameters
factoryMethodFunc<T>Optional factory delegate used to create new instances when the pool is empty. Defaults to
new T()if not supplied.initialCapacityintNumber of instances to pre-warm the pool with.
Properties
Count
The number of instances currently sitting idle in the pool.
public int Count { get; }
Property Value
Methods
Get()
Returns a pooled instance if one is available; otherwise creates a new one via the factory.
public T Get()
Returns
- T
Release(T)
Returns an instance to the pool so it can be reused later. Ensure the object is fully reset before or after calling this method.
public void Release(T obj)
Parameters
objTThe instance to return to the pool.