Prototype pattern vs Closure proto pattern (v3)

Revision 3 of this benchmark created on


Description

The closure proto pattern allows a few nifty tricks, such as private variables and setting the prototype dynamically during runtime. But how does it affect performance?

Test runner

Ready to run.

Testing in
TestOps/sec
Prototype pattern
function Foo(val) {
  this.val = val;
}

Foo.prototype.getVal = function() {
  return this.val;
}

var objects = [];
for (var i = 0; i < 100; i++) {
  objects.push(new Foo(i));
  objects[i].getVal();
}
ready
Closure proto pattern
function Parent() {

}

Parent.prototype.getVal = function() {
  return this.val;
}

function foo(val) {
  function Obj() {
    this.val = val;
  }

  Obj.prototype = new Parent();

  return new Obj();
}

var objects = [];
for (var i = 0; i < 100; i++) {
  objects.push(foo(i));
  objects[i].getVal();
}
ready
private
function foo(val){
    return {
        getVal : function(){
            return val;
        }
    };
}

var objects = [];
for (var i = 0; i < 100; i++) {
  objects.push(foo(i));
  objects[i].getVal();
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.