Prototype Pattern With Variable Reference To Prototype Functions

Benchmark created on


Description

Can you gain a performance boost in the prototype pattern by adding a reference to functions on the prototype?

Three "Classes"... Customer1: Prototype Customer2: Prototype with reference Customer3: Closure

In Customer2, I add a variable in the constructor: this.greet = this.constructor.prototype.greet; The idea is to increase performance by adding a direct reference to the prototype's function meaning it shouldn't have to traverse the prototype chain as far.

The tests are split between setting up the objects and calling functions on pre-created objects. In the tests P is Prototype, PR is Prototype with Reference, and Cl is Closure.

Setup

function Customer1(name) {
        this.name = name;
    }
    Customer1.prototype = {
        constructor: Customer1,
        greet: function () {
            return this.name + ' says hi!';
        }
    };
    
    function Customer2(name) {
        this.name = name;
        this.greet = this.constructor.prototype.greet;
    }
    Customer2.prototype = {
        constructor: Customer2,
        greet: function () {
            return this.name + ' says hi!';
        }
    };
    
    function Customer3(name) {
        var _name = name;
        this.greet = function() {
            return _name + ' says hi!';
        };
    }
    
    var c4 = new Customer1();
    var c5 = new Customer2();
    var c6 = new Customer3();

Test runner

Ready to run.

Testing in
TestOps/sec
P Setup
var c1 = new Customer1();
ready
PR Setup
var c2 = new Customer2();
ready
Cl Setup
var c3 = new Customer3();
ready
P Func
c4.greet();
ready
PR Func
c5.greet();
ready
Cl Func
c6.greet();
ready

Revisions

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