Skip to content

Instantly share code, notes, and snippets.

@YonatanKra
Last active October 28, 2020 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YonatanKra/c3899fcf0f0556a7a4ae0d73589df9f4 to your computer and use it in GitHub Desktop.
Save YonatanKra/c3899fcf0f0556a7a4ae0d73589df9f4 to your computer and use it in GitHub Desktop.
Non-performant object pool
class ObjectPool {
constructor(objectConstructor, objectReseter, initialSize = 5000) {
this.objectConstructor = objectConstructor;
this.objectReseter = objectReseter;
this._pool = [];
for (let i = 0; i < initialSize; i++) {
this._addObjectToPool();
}
}
_addObjectToPool() {
const newObj = {
alive: false,
data: this.objectConstructor()
};
this._pool.push(newObj);
}
_allocate(object) {
object.alive = true;
return object;
}
getNew() {
for (let i = 0; i < this._pool.length; i++) {
if (this._pool[i].alive === false) {
return this._allocate(this._pool[i]);
}
}
return this._addObjectToPool();
}
release(object) {
object.alive = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment