instance vs prototype methods

JavaScript performance comparison

Test case created by bogdan

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function inherit(subClass, superClass) {
      subClass.prototype = new superClass();
      subClass.prototype.constructor = subClass;
      subClass.prototype.parent = superClass.prototype;
    }
   
    function Person(options) {
      // initialize instance members
      options = options || {};
      this.name = options.name || "no name";
      this.age = options.age || 0;
    }
   
    Person.prototype.talk = function() {
      return "Hello, I'm " + this.name;
    }
   
    function Worker(options) {
   
      if (this.parent) this.parent.constructor.apply(this, arguments);
   
      options = options || {};
   
      this.action = options.action || 'programming';
   
      this.work = function() {
        return this.name + ' works in ' + this.action;
      }
    }
   
    function Programmer(options) {
      options = options || {};
   
      this.action = 'coding';
      this.language = options.language || 'in PHP';
      this.code = function() {
        return this.work() + ' ' + this.language;
      }
    }
   
    function ProtoWorker(options) {
   
      if (this.parent) this.parent.constructor.apply(this, arguments);
   
      options = options || {};
   
      this.action = options.action || 'programming';
   
    }
    ProtoWorker.prototype.work = function() {
      return this.name + ' works in ' + this.action;
    }
   
    function ProtoProgrammer(options) {
      options = options || {};
   
      this.action = 'coding';
      this.language = options.language || 'in PHP';
    }
   
    ProtoProgrammer.prototype.code = function() {
      return this.work() + ' ' + this.language;
    }
   
    inherit(Worker, Person);
    inherit(Programmer, Worker);
   
    inherit(ProtoWorker, Person);
    inherit(ProtoProgrammer, ProtoWorker);
   
    var myP, protoProgrammer;
};
</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
instance method
myP = new Programmer({
  name: 'Gigi'
});
myP.code()
pending…
prototype method
protoProgrammer = new Programmer({
  name: 'Gigi'
});
protoProgrammer.code();
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

Add a comment