mpool
This library provides a simple object pool implementation.
Usage
import { Pool } from "mpool";
const pool = new Pool(() => ({ value: 0 }));
const obj = pool.get();
use(obj);
pool.put(obj);
The pool is unbounded, meaning that the pool never discards objects. To mitigate unbounded memory growth scenarios, the pool contains a .fit()
method which shrinks the pool to pool.preferredSize
objects, if there are more than pool.preferredSize
objects in the pool. You may call this at the end of your game loop.
import { Pool } from "mpool";
class Thing {}
const pool = new Pool(() => new Thing, 5);
console.log(pool.length);
pool.put(new Thing);
console.log(pool.length);
pool.fit();
console.log(pool.length);
The recommended way to handle initialization + deinitialization of your objects is to implement init
and free
, for example:
import { Pool } from "mpool";
class Thing {
public value!: number;
init(value: number): this {
this.value = value;
return this;
}
free() {
console.log(`freed object: Thing { value: ${this.value} }`);
return this;
}
}
const pool = new Pool(
() => new Thing,
o => o.free(),
0
);
const obj = pool.get().init(100);
use(obj);
pool.put(obj);
pool.fit();