Prototype vs. this (v23)

Revision 23 of this benchmark created on


Setup

var iterationCount = 25000;
    
    function T1(x) {
      this.x = -x;
    }
    
    T1.prototype.myMethod = function(n) {
      if (n === this.x) console.log('T1 match');
    };
    
    function T2(x) {
      this.x = -x;
      this.myMethod = function(n) {
        if (n === this.x) console.log('T2 match');
      };
    }
    
    
    function T3(x) {
      var instance = {
        x: -x,
        myMethod: function(n) {
          if (n === this.x) console.log('T3 match');
        }
      }
      return instance;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Using prototype
var i = 0;
while (i < iterationCount) {
  t1 = new T1(i);
  t1.myMethod(i++);
}
ready
Using this
var i = 0;
while (i < iterationCount) {
  t2 = new T2(i);
  t2.myMethod(i++);
}
ready
Using short notation object
var i = 0;
while (i < iterationCount) {
  t3 = T3(i);
  t3.myMethod(i++);
}
ready

Revisions

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