Last active
October 30, 2024 18:36
-
-
Save mimshins/cf731458dab84637f323b56e1f8fb2d2 to your computer and use it in GitHub Desktop.
Simple Array 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 ArrayPool<T> { | |
private _pool: T[][] = []; | |
private readonly _maxPoolSize: number; | |
constructor(maxPoolSize: number = 10) { | |
this._maxPoolSize = maxPoolSize; | |
} | |
// Get an array from the pool, or create a new one if the pool is empty | |
public getArray(size: number): T[] { | |
const array = this._pool.length > 0 ? this._pool.pop()! : Array.from({ length: size }); | |
// Ensure the array is the correct size | |
array.length = size; | |
return array; | |
} | |
// Return an array to the pool | |
public returnArray(array: T[]): void { | |
if (this._pool.length >= this._maxPoolSize) return; | |
// Reset array length to 0 | |
array.length = 0; | |
this._pool.push(array); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment