Last active
August 29, 2015 14:09
-
-
Save KrofDrakula/670f505b13c77c0be090 to your computer and use it in GitHub Desktop.
Object pooling implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ObjectPool(Type) { | |
this.Type = Type; | |
this.available = []; | |
this.active = []; | |
} | |
ObjectPool.prototype.create = function() { | |
var args = [].slice.apply(arguments), self = this, inst, ret; | |
if (this.available.length == 0) { | |
var Temp = function() {}; | |
Temp.prototype = this.Type.prototype; | |
inst = new Temp; | |
inst.destroy = function() { self.recycle(inst); }; | |
} else { | |
inst = this.available.pop(); | |
} | |
this.active.push(inst); | |
ret = this.Type.apply(inst, args); | |
ret = Object(ret) === ret ? ret : inst; | |
return ret; | |
}; | |
ObjectPool.prototype.recycle = function(item) { | |
var idx = this.active.indexOf(item); | |
this.active.splice(idx, 1); | |
this.available.push(item); | |
item.reset(); | |
}; | |
function Vec2(x, y) { | |
this.x = x * 1; | |
this.y = y * 1; | |
} | |
Vec2._pool = new ObjectPool(Vec2); | |
Vec2.create = function(x, y) { | |
return this._pool.create(x, y); | |
}; | |
Vec2.prototype.clone = function() { | |
return Vec2.create(this.x, this.y); | |
}; | |
Vec2.prototype.add = function(vec) { | |
this.x += vec.x; | |
this.y += vec.y; | |
return this; | |
}; | |
Vec2.prototype.sub = function(vec) { | |
this.x -= vec.x; | |
this.y -= vec.y; | |
return this; | |
}; | |
Vec2.prototype.scale = function(s) { | |
this.x *= s; | |
this.y *= s; | |
return this; | |
}; | |
Vec2.prototype.neg = function() { | |
this.scale(-1); | |
return this; | |
}; | |
Vec2.prototype.dot = function(vec) { | |
return this.x * vec.x + this.y * vec.y; | |
}; | |
Vec2.prototype.normalize = function() { | |
var l = this.length; | |
this.scale(l == 0 ? 0 : 1 / l); | |
return this; | |
}; | |
Vec2.prototype.reset = function() { | |
this.x = this.y = 0; | |
}; | |
Object.defineProperty(Vec2.prototype, 'length', { | |
get: function() { return Math.sqrt(this.dot(this)); } | |
}); | |
var a = Vec2.create(1, 2), b = Vec2.create(3, 4), c = Vec2.create(5, 6), d = a.clone(); | |
console.log(Vec2._pool); | |
console.log('============='); | |
a.add(b).add(c).add(d); | |
a.destroy(); | |
b.destroy(); | |
console.log(Vec2._pool); | |
console.log('============='); | |
a = Vec2.create(7, 8); | |
b = Vec2.create(9, 10); | |
console.log(Vec2._pool); | |
console.log('============='); | |
a.destroy(); | |
b.destroy(); | |
c.destroy(); | |
d.destroy(); | |
console.log(Vec2._pool); | |
console.log('============='); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment