Skip to content

Instantly share code, notes, and snippets.

@mimshins
Last active October 30, 2024 18:35
Show Gist options
  • Save mimshins/23535f032e026d7245eb7aff8145cc47 to your computer and use it in GitHub Desktop.
Save mimshins/23535f032e026d7245eb7aff8145cc47 to your computer and use it in GitHub Desktop.
Simple Object Pool Implementation
class ObjectPool<T> {
private _pool: T[] = [];
private readonly _createObject: () => T;
private readonly _resetObject: (obj: T) => void;
private readonly _maxPoolSize: number;
constructor(creator: () => T, reset: (obj: T) => void, maxPoolSize: number = 10) {
this._createObject = creator;
this._resetObject = reset;
this._maxPoolSize = maxPoolSize;
}
// Get an object from the pool, or create a new one if the pool is empty
public getObject(): T {
return this._pool.length > 0 ? this._pool.pop()! : this._createObject();
}
// Return an object to the pool
public returnObject(obj: T): void {
if (this._pool.length >= this._maxPoolSize) return;
this._resetObject(obj);
this._pool.push(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment