12

鉴于这个非常熟悉的原型构建模型:

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

谁能解释为什么调用new Rectangle(2,3)总是比Rectangle(2,3)没有“新”关键字的调用快 10 倍?我会假设,因为 new 通过涉及原型增加了函数执行的复杂性,所以它会更慢。

例子:

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);

产量(在 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
4

1 回答 1

17

当你调用没有“new”的函数时,你怀疑“this”指向的是什么?这将是“窗口”。当您使用“new”调用它时,更新它比更新您将使用的新构建的新对象要慢。

将第二个版本更改为:

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

看看你得到了什么。另一件要尝试的事情是:

trackFunction('rect with constant object', (function() {
  var object = { height: 0, width: 0 };
  return function() {
    Rectangle.call(object, 2, 3);
  };
})());

这将节省在每次迭代中重建虚拟对象的成本。

于 2010-03-24T15:34:06.080 回答