Prototype vs Module pattern performance (v181)

Revision 181 of this benchmark created by S H on


Setup

var inherit = function(obj) {                           // make a dummy object that has prototype as obj
        var F = function () {};
        F.prototype = obj;
        return new F();
    };
    
    var Shape = function (color) {                          // constructor
        this.color = color;
    };
    
    Shape.prototype.get_color = function () {
        return this.color;
    };
    
    Shape.prototype.area = function() {
        return 0.0;
    };
    
    var Rectangle = function (color, height, width) {
        Shape.apply(this, [color]);
        this.height = height;
        this.width = width;
    };
    
    Rectangle.prototype = inherit(Shape.prototype);         
    
    Rectangle.prototype.area = function () {
        return this.height * this.width;
    };
    
    var shape = function (color) {
        var that = {};
    
        that.get_color = function () {
                return color;
        };
    
        that.area = function () {
                return 0.0;
        };
    
        return that;
    };
    
    var rectangle = function (color, height, width) {
        var that = shape(color);   
    
        that.area = function () {
            return height * width;
        };
    
        return that;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Prototypal
var s = new Shape("blue");                              // new keyword to create object from constructor
var r = new Rectangle("green", 10, 8);
ready
Module pattern
var s = shape("blue");                            // this is not a constructor, so no new keyword
var r = rectangle("green", 10, 8);
ready

Revisions

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