prototype vs closures

JavaScript performance comparison

Revision 11 of this test case created by Simone Deponti

Preparation code

<script>
  function Shoes(color) {
      this.color = color;
  }
  
  Shoes.prototype.get_color = function() {
      return this.color;
  }
  
  Shoes.prototype.set_color = function(newColor) {
      this.color = newColor;
  }
  
  function Person(name, shoes) {
      this.name = name;
      this.shoes = shoes;
  }
  
  Person.prototype.get_name = function() {
      return this.name;
  };
  
  Person.prototype.set_name = function(name) {
      this.name = name;
  };
  
  function shoes(color) {
      return {
          color: color,
          get_color: function() { return this.color; },
          set_color: function(newColor) { this.color = newColor; }
      }
  }
  
  function person(name, shoes){
  	return {
  		name:name, 
                  shoes:shoes,
  		get_name: function() { return this.name; }, 
  		set_name: function(newName) { this.name = newName }
  	}
  }
  
</script>
      
<script>
Benchmark.prototype.setup = function() {
  var proto_shoes = new Shoes('Red');
  var closure_shoes = shoes('Red');
  var proto = new Person('John', proto_shoes);
  var closure = person('John', closure_shoes);
  var mapping = {
  	name : 'John',
          shoes: {
              color: 'Red',
              get_color: function() { return this.color; },
              set_color: function(newColor) { this.color = newColor; }
          },
  	get_name: function() { return this.name; }, 
  	set_name: function(newName) { this.name = newName }
  }
  

};
</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 init
var _proto_shoes = new Shoes('Red');
var _proto = new Person('John', _proto_shoes);
pending…
Closure init
var _closure = person('John', shoes('Red'));
pending…
Prototype read
proto.get_name();
proto.shoes.get_color();
pending…
Closure read
closure.get_name();
closure.shoes.get_color();
pending…
Prototype write
proto.set_name('Jane');
proto.shoes.set_color('Green');
pending…
Closure write
closure.set_name('Jane');
closure.shoes.set_color('Green');
pending…
HEH read
mapping.get_name();
mapping.shoes.get_color();
pending…
HEH write
mapping.set_name('Jane')
mapping.shoes.set_color('Green');
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.

0 Comments