Calling function using 'new' is less expensive than without it?

Posted by Matthew Taylor on Stack Overflow See other posts from Stack Overflow or by Matthew Taylor
Published on 2010-03-24T15:31:13Z Indexed on 2010/03/24 15:33 UTC
Read the original article Hit count: 381

Given this very familiar model of prototypal construction:

function Rectangle(w,h) {
    this.width = w;
    this.height = h;
}
Rectangle.prototype.area = function() { 
    return this.width * this.height;
};

Can anyone explain why calling "new Rectangle(2,3)" is consistently 10x FASTER than calling "Rectangle(2,3)" without the 'new' keyword? I would have assumed that because new adds more complexity to the execution of a function by getting prototypes involved, it would be slower.

Example:

var myTime;
function startTrack() {
    myTime = new Date();
}
function stopTrack(str) {
    var diff = new Date().getTime() - myTime.getTime();
    println(str + ' time in ms: ' + diff);
}

function trackFunction(desc, func, times) {
    var i;
    if (!times) times = 1;
    startTrack();
    for (i=0; i<times; i++) {
        func();
    }
    stopTrack('(' + times + ' times) ' + desc);
}

var TIMES = 1000000;

trackFunction('new rect classic', function() {
    new Rectangle(2,3);
}, TIMES);

trackFunction('rect classic (without new)', function() {
    Rectangle(2,3);
}, TIMES);

Yields (in Chrome):

(1000000 times) new rect classic time in ms: 33
(1000000 times) rect classic (without new) time in ms: 368

(1000000 times) new rect classic time in ms: 35
(1000000 times) rect classic (without new) time in ms: 374

(1000000 times) new rect classic time in ms: 31
(1000000 times) rect classic (without new) time in ms: 368

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about constructors