ObjectPool
The ObjectPool class is designed to manage object pooling, a technique that optimizes resource reuse by recycling objects instead of frequently creating and destroying them.
constructor(createFn: CreateFunction, initialSize?: number)
This class allows users to define custom object creation logic and manage the pool of objects efficiently.
Parameters:
createFn
: A delegate function responsible for creating new objects.initialSize
(optional): The initial number of objects to pre-create and store in the pool. Defaults to 10.
Example:
const pool = new ObjectPool(() => ({x:0, y:0}), 20);
acquire(): any
Retrieves an object from the pool. If the pool has available objects, it will return one of them. If the pool is empty, it will create a new object using the createFn
function.
Example:
const obj = pool.acquire();
release(object: any): void
Releases an object back into the pool, making it available for reuse.
Parameters:
object
: The object to be released back into the pool.
Example:
pool.release(obj);
size(): number
Returns the current number of objects available in the pool.
Example:
console.log(pool.size());
resize(newSize: number): void
Allows dynamic resizing by adding more objects when necessary.
Parameters:
newSize
: The target size for the pool.
Example:
pool.resize(50);
shuffle(): void
Randomly reorders the objects in the pool, ensuring a uniform random distribution of the objects.
Example:
pool.shuffle();