Functions in prototype vs object itself

JavaScript performance comparison

Test case created by mgibsonbr and last updated

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function Prototype(x, y, z) {
      this.x = x;
      this.y = y;
      this.z = z;
  }
  Prototype.prototype.foo = function() {
      return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);
  };
  
  function OwnObject(x, y, z) {
      this.x = x;
      this.y = y;
      this.z = z;
      this.foo = function() {
          return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);
      };
  }
  
  function foo() {
      return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);
  };
  function SharedFunction(x, y, z) {
      this.x = x;
      this.y = y;
      this.z = z;
      this.foo = foo;
  }
  
  function Closure(x, y, z) {
      this.x = x;
      this.y = y;
      this.z = z;
      this.foo = function() {
          return Math.sqrt(x*x + y*y + z*z);
      };
  }
  
  function test(constructor) {
      var array = [];
      for ( var i = 0 ; i < 50 ; i++ )
          for ( var t = 0 ; t < 50 ; t++ )
              for ( var k = 0 ; k < 50 ; k++ )
                  array[2500*i+50*t+k] = new constructor(i,t,k);
  
      for ( var i = 0 ; i < array.length ; i++ )
          array[i].foo();
  }
  

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Prototype
test(Prototype);
pending…
Own Object
test(OwnObject);
pending…
Shared Function
test(SharedFunction);
pending…
Closure
test(Closure);
pending…

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

Compare results of other browsers

0 Comments