Skip to content

Instantly share code, notes, and snippets.

@epreston
Created April 29, 2023 09:22
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 epreston/ca956d15485092ca59ddc36edbf465d8 to your computer and use it in GitHub Desktop.
Save epreston/ca956d15485092ca59ddc36edbf465d8 to your computer and use it in GitHub Desktop.
add object pool support to a prototype - avoid small object allocation with reuse - alloc, get, release
const isFn = (a) => typeof a === 'function';
export function addObjectPool(objtype, resetFunction, maxSize = Number.MAX_SAFE_INTEGER) {
const pool = [];
function newObject() {
return new objtype();
}
if (isFn(resetFunction)) {
objtype.prototype.onPoolReset = resetFunction;
}
objtype.prototype.release = function () {
objtype.release(this);
return this;
};
objtype.alloc = (count) => {
if (!(count <= 0)) for (; count--; ) objtype.release(newObject());
};
objtype.get = () => {
const object = pool.pop() || newObject();
object.onPoolReset && object.onPoolReset(object);
return object;
};
objtype.release = (...args) => {
let index = args.length;
for (; index--; ) pool.length < maxSize && pool.push(args[index]);
};
return objtype;
}
@epreston
Copy link
Author

Example:

Given a class that has some way to reset its values to default, or this can be done in a reset funciton, we call this Functional Mixin to add object pool support. In this case, the example object already has a resetTo method that can do this.

// add pool methods:  alloc, get, release
addObjectPool(ClassName, (instance) => instance.resetTo(0));

// optional: allocate 10 objects
ClassName.alloc(10);

// get an object from the pool
const obj = ClassName.get();

// return the object to the pool
obj.release();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment