Skip to content

Instantly share code, notes, and snippets.

@louisstow
Last active September 14, 2021 14:46
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save louisstow/5609992 to your computer and use it in GitHub Desktop.
Save louisstow/5609992 to your computer and use it in GitHub Desktop.
Generic object pool in JavaScript
var objectPool = [];
var marker = 0;
var poolSize = 0;
//any old JavaScript object
function commonObject () { }
commonObject.create = function () {
if (marker >= poolSize) {
commonObject.expandPool(poolSize * 2);
}
var obj = objectPool[marker++];
obj.index = marker - 1;
obj.constructor.apply(obj, arguments);
return obj;
}
//push new objects onto the pool
commonObject.expandPool = function (newSize) {
for (var i = 0; i < newSize - poolSize; ++i) {
objectPool.push(new commonObject());
}
poolSize = newSize;
}
//swap it with the last available object
commonObject.prototype.destroy = function () {
marker--;
var end = objectPool[marker];
var endIndex = end.index;
objectPool[marker] = this;
objectPool[this.index] = end;
end.index = this.index;
this.index = endIndex;
}
//make this as big as you think you need
commonObject.expandPool(1000);
@louisstow
Copy link
Author

Usage

  1. Replace commonObject with the name of your JavaScript class.
  2. Expand the pool to the size that you think you might need. If it overflows, it will expand the pool to twice it's current size
  3. Only create objects through commonObject.create(...). You can pass any data as if it was the constructor.
  4. When you are finished with the object call the .destroy() method on the instance.

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