Skip to content

Instantly share code, notes, and snippets.

@mimshins
Last active October 30, 2024 18:36
Show Gist options
  • Save mimshins/cf731458dab84637f323b56e1f8fb2d2 to your computer and use it in GitHub Desktop.
Save mimshins/cf731458dab84637f323b56e1f8fb2d2 to your computer and use it in GitHub Desktop.
Simple Array Pool Implementation
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