Skip to content

Instantly share code, notes, and snippets.

@stickupkid
Created September 25, 2012 10:01
Show Gist options
  • Save stickupkid/3781004 to your computer and use it in GitHub Desktop.
Save stickupkid/3781004 to your computer and use it in GitHub Desktop.
Object Pool in javascript.
var Task0 = function() {}
Task0.prototype = {
init: function(value) {
this.value = value;
}
};
var Task1 = {
init: function(value) {
this.value = value;
}
};
var Pool = {
generate: function() {
this._pool = [];
for (var i = 0, total = 900000; i < total; i++) {
this._pool.push(Object.create(Task1));
}
this._pointer = total - 1;
},
get: function() {
return this._pool[this._pointer--];
},
set: function(value) {
this._pointer++;
}
};
var pool = Object.create(Pool);
pool.generate();
var date0 = new Date().valueOf();
var total = 900000;
while(--total > -1) {
new Task0().init(total);
}
var date1 = new Date().valueOf();
var total = 900000;
while (--total > -1) {
pool.get().init(total);
}
var date2 = new Date().valueOf();
console.log(date1 - date0);
console.log(date2 - date1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment