JScript高速化(3)

具体的な問題に入っていこう。

copy


var p = new poly([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]);
for(var i = 0; i < n; i++)
var r = p.copy();

を速くすることを考えよう。
ここで、polyの係数はfractionでなく値とする。
copyは、


function poly() {
var args = poly.arguments;
if(args.length == 0)
this.a = [ 0 ];
else {
this.a = [ ];
for(var i = 0; i < args.length; i++) {
var b = args[i];
if(typeof b == "number")
this.a.push(b);
else if(b instanceof Array) {
for(var j = 0; j < b.length; j++)
this.a.push(b[j]);
}
}
}

// コピー
this.copy = function() {
return new poly(this.a);
}
...
}

だから、かなりムダなことをしている。
コピーを次のように変える。


this.copy2 = function() {
var r = new poly();
for(var j = 0; j < this.a.length; j++)
r.a[j] = this.a[j];
return r;
}

copy:1019ms
copy2:806ms
だが、nが1桁小さい。
昨日とほとんど同じことをやっているはずなのに、
なぜこんなに遅い?


// 586ms(コピーではないが)
this.copy3 = function() {
var r = new poly();
return r;
}

差を取って10倍すると、2200msだからあってる。
結局、newが遅いのか?
こうすると、


function poly() {
this.a = [ 0 ];

this.copy3 = function() {
var r = new poly();
return r;
}
}

243msか。
コンストラクタが重いのが大きいということか。