compostable objects

JavaScript performance comparison

Revision 4 of this test case created by Joshua Piccari

Info

What kind of performance gains do we see when reusing objects rather than creating and destroying.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var coordsNew = [],
      coordsCompost = [],
      len = 1e6;
   
    while (--len) {
      coordsNew.push(new Point(Math.random(), Math.random()));
      coordsCompost.push(new Point(Math.random(), Math.random()));
    }
   
    function compostable(fn) {
      var instances = [],
        available = [];
   
      fn.create = function() {
        var instance = available.pop();
   
        if (!instance) {
          instance = Object.create(fn.prototype);
          instances.push(instance);
        }
   
        fn.apply(instance, arguments);
   
        return instance;
      };
   
      fn.prototype.compost = function() {
        available.push(this);
      };
   
      return fn;
    }
   
   
    function Point(x, y) {
      this.x = x;
      this.y = y;
    }
   
    compostable(Point);
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Control (new object)
for (var i = 0; i < coordsNew.length; i++) {
  coordsNew[i] = new Point(i * i, Math.pow(i, i));
}
pending…
Compostable
for (var i = 0; i < coordsCompost.length; i++) {
  coordsCompost[i].compost();
  coordsCompost[i] = Point.create(i * i, Math.pow(i, i));
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment