Last active
October 30, 2024 18:35
-
-
Save mimshins/23535f032e026d7245eb7aff8145cc47 to your computer and use it in GitHub Desktop.
Simple Object Pool Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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