Correct way to declare prototype functions

JavaScript performance comparison

Revision 4 of this test case created by Artem Chudinov

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var Object1 = function() {}
   
    Object1.prototype.defaults = {
        radius: 400,
        up: 1
    }
   
    Object1.prototype.centerOffset = function() {
        return this.defaults.radius*this.defaults.up;
    }
   
    var Object2 = function() {}
   
    Object2.prototype = {
        defaults: {
            radius: 400,
            up: 1
        },
   
        centerOffset: function() {
            return this.defaults.radius*this.defaults.up;
        }
    }
   
    var Object3 = function() {}
   
    Object3.prototype = {
        radius: 400,
        up: 1,
        centerOffset: function() {
            return this.radius*this.up;
        }
    }
   
    var Object4 = function() {
        this.init = function() {
            this.radius = 400;
            this.up = 1;
        };
        this.centerOffset = function() {
            return this.radius*this.up;
        };
    }
   
    var Object5 = function() {
        this.radius = 400;
        this.up = 1;
        this.centerOffset = function() {
            return this.radius*this.up;
        };
    }
   
    var Object6 = {
        radius: 400,
        up: 1,
        centerOffset: function() {
            return this.radius*this.up;
        }
    }
};
</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
Define prototype functions separately
var o = new Object1();
var offset = o.centerOffset();
pending…
Define prototype functions in a dictionary
var o = new Object2();
var offset = o.centerOffset();
pending…
With no .defaults
var o = new Object3();
var offset = o.centerOffset();
pending…
Just an object dynamically created with initialization
var o = new Object4();
o.init();
var offset = o.centerOffset();
pending…
Just an object dynamically created
var o = new Object5();
var offset = o.centerOffset();
pending…
Just an object
var o = Object6;
var offset = o.centerOffset();
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