Prototype vs Factory Method Performance

JavaScript performance comparison

Revision 9 of this test case created by Esailija

Preparation code

<script>


    function createValueObject() {
      var x = 0.1;
   
      function get() {
        return x;
      }
   
      function add(y) {
        x += y;
      }
   
      function subtract(y) {
        x -= y;
      }
   
      function multiply(y) {
        x *= y;
      }
   
      function divide(y) {
        x /= y;
      }
   
      function mod(y) {
        x %= y;
      }
   
      return {
        get: get,
        add: add,
        subtract: subtract,
        multiply: multiply,
        divide: divide,
        mod: mod
      };
    }
   
    function ValueObject() {
      this.x = 0.1;
    }
   
    ValueObject.prototype.get = function() {
      return this.x;
    };
   
    ValueObject.prototype.add = function(y) {
      this.x += y;
    };
   
    ValueObject.prototype.subtract = function(y) {
      this.x -= y;
    };
   
    ValueObject.prototype.multiply = function(y) {
      this.x *= y;
    };
   
    ValueObject.prototype.divide = function(y) {
      this.x /= y;
    };
   
    ValueObject.prototype.mod = function(y) {
      this.x %= y;
    };

var l = 10000;
while(l--) {
var x = createValueObject();
var y = new ValueObject();
x.add(5);
x.subtract(3);
x.multiply(3);
x.divide(2);
x.mod(2);
y.add(5);
y.subtract(3);
y.multiply(3);
y.divide(2);
y.mod(2);
}


</script>
<script>
Benchmark.prototype.setup = function() {
    var x = window.x;
    var y = window.y;
};

Benchmark.prototype.teardown = function() {
    console.log(x, y);
};
</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
Factory
x.add(5);
x.subtract(3);
x.multiply(3);
x.divide(2);
x.mod(2);
 
pending…
Prototype
y.add(5);
y.subtract(3);
y.multiply(3);
y.divide(2);
y.mod(2);
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