Prototype vs Module pattern performance (v120)

Revision 120 of this benchmark created by Mark Avery on


Description

Removed iterations in tests, because jsperf already does that for us. And renamed variables to be more meaningful to us humans. And other cosmetic changes.

The most important thing to remember is to use the right tool for the job. All these tests do is reference an object with a complex memory allocation. When you don't need something fancy, you're better off using a regular old object

Setup

function TraditionalPrototypeClass() {}
    
    TraditionalPrototypeClass.prototype.foo = function(test) {
      test = test * test * test;
      test--;
      return test;
    };
    
    TraditionalPrototypeClass.prototype.bar = function(test) {
      return this.foo(test) * this.foo(test);
    };
    
    function ModulePatternClass() {
      this.foo = function(test) {
        test = test * test * test;
        test--;
        return test;
      };
    
      this.bar = function(test) {
        return this.foo(test) * this.foo(test);
      };
    }
    
    var ModuleCachePatternClass = (function() {
      function foo(test) {
        test = test * test * test;
        test--;
        return test;
      }
    
      function bar(test) {
        return this.foo(test) * this.foo(test);
      }
    
      return function() {
        this.foo = foo;
        this.bar = bar;
      };
    }());
    
    var standardObject = {
      foo: function(test) {
        test = test * test * test;
        test--;
        return test;
      },
      bar: function(test) {
        return this.foo(test) * this.foo(test);
      }
    };

Test runner

Ready to run.

Testing in
TestOps/sec
Prototypal
var o = new TraditionalPrototypeClass();
o.bar(33)
ready
Module pattern
var o = new ModulePatternClass();
o.bar(33)
ready
Module pattern with cached functions
var o = new ModuleCachePatternClass();
o.bar(33)
ready
Use the right tool for the job
var o = standardObject;
o.bar(33)
ready

Revisions

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