Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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);
Owner

louisstow commented May 20, 2013

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