Skip to content

Instantly share code, notes, and snippets.

@wthit56
Last active December 10, 2015 11:29
Show Gist options
  • Save wthit56/4427983 to your computer and use it in GitHub Desktop.
Save wthit56/4427983 to your computer and use it in GitHub Desktop.
Reusing objects to avoid Garbage Collection
// run here (use the data-uri below as an address):
// data:text/html;ascii,<script src="https://gist.github.com/raw/4427983/9bd86a469ad84effee2daffad03909a25d4200a2/gistfile1.js" type="text/javascript"></script>
var Reusable = (function () {
// used to cache any clean objects for reuse
var clean = [];
function Reusable(value) {
console.group("creating new object");
var _ = this;
// clean objects are available for reuse...
if (clean.length > 0) {
console.log("clean objects available; using last");
// ...so use the last item
_ = Reusable.init.apply(clean.pop(), arguments);
}
else {
console.log("new object created");
}
// initialize object
_ = Reusable.init.apply(_, arguments);
return _;
};
// this method do any instantiation
// and is called for new and reused objects
Reusable.init = function (value) {
this.value = value;
console.log("value applied");
console.groupEnd();
return this;
};
Reusable.prototype = {
value: -1,
// calling this method will clean the object and make it available for reuse
// when next instantiating a new object
clean: function () {
console.group("cleaning object");
// reset values, dispose of any objects, etc.
this.value = Reusable.prototype.value;
// add the object to the "clean" cache for reuse when creating a new object
clean.push(this);
console.log("object cleaned");
console.log(clean.length + " clean objects available");
console.groupEnd();
return this;
}
};
return Reusable;
})();
// console shim
(function () {
if (!window.console) { window.console = {}; }
var c = window.console;
if (!c.log) { c.log = function () { }; }
if (!c.group) { c.group = function (label) { c.log("__" + label + "__"); }; }
if (!c.groupEnd) { c.groupEnd = function () { }; }
})();
// test
var a = new Reusable(1);
var b = new Reusable(2);
a.clean();
var c = new Reusable(3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment