Prototype vs instance functions (v14)

Revision 14 of this benchmark created by Alex Frase on


Description

The choice between instance and prototype methods is not as simple as putting them inside or outside the constructor. In any real environment, the method is going to have to access properties of the object (otherwise, why is it a method and not a standalone function?). Given that expectation, a prototyped method incurs the additional cost of referencing object properties as "this.property" rather than simply "property" via closure.

We also probably won't be creating new object as often as calling their methods, and this test case is aimed at method definition anyway, so we should move the "new" outside the loop to get a better sense of the actual method call overhead of the two approaches, without being skewed by the object instantiation overhead.

Test runner

Ready to run.

Testing in
TestOps/sec
Instance
var myClass = function(x, y){
    this.method = function(){
        return x + y;
    }
};

var instance = new myClass(1, 2);
for(var i = 0; i < 10000; i++){
    instance.method();
};
ready
Prototype
var myClass = function(x, y){
    this.x = x;
    this.y = y;
};

myClass.prototype.method = function(){
    return this.x + this.y;
};

var instance = new myClass(1, 2);
for(var i = 0; i < 10000; i++){
    instance.method();
};
ready

Revisions

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