プロトタイプ構造のこの非常によく知られているモデルを考えると:
function Rectangle(w,h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return this.width * this.height;
};
'new'キーワードなしnew Rectangle(2,3)
で呼び出すよりも、呼び出しが一貫して10倍高速である理由を誰かが説明できますか?Rectangle(2,3)
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