prototype vs closures

JavaScript performance comparison

Revision 2 of this test case created

Info

Prototype and Closure approach comparison

Preparation code

<script>
  function Person(name) {
      this.name = name;
  }
 
  Person.prototype.get_name = function() {
      return this.name;
  };
 
  Person.prototype.set_name = function(name) {
      this.name = name;
  };
 
  var person = function(name) {
          return {
              'get_name': function() {
                  return name;
              },
              'set_name': function(newName) {
                  name = newName;
              }
          };
      };
 
  var c = new Person('John');
  var b = person('John');
 
  ui.benchmarks[2].setup = function() {
      var b = new Person('John');
  };
 
  ui.benchmarks[3].setup = function() {
      var c = person('John');
  };
 
  ui.benchmarks[4].setup = ui.benchmarks[2].setup;
  ui.benchmarks[5].setup = ui.benchmarks[3].setup;
</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
Prototype init
var c = new Person('John');
pending…
Closure init
var b = person('John');
pending…
Prototype read
c.get_name();
pending…
Closure read
b.get_name();
pending…
Prototype write
c.set_name('Jane');
pending…
Closure write
b.set_name('Jane');
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:

2 comments

Jason Mulligan commented :

This is declarative vs literal, they're both prototypal.

Thadeu de Paula commented :

In a server, with node, this performace matters... but in browsers, in daily use, with compressors, the need of a global environment cleaner and with no need of many instances, closures can be a better choice.

Add a comment