JScript高速化(15)

あと高速化していないのは、合成のメソッドくらいだが、


// 合成
function poly_synthesize(p) {
if(!(p instanceof poly))
throw("unsupported argument in poly::synthesize");

var r = new poly();
for(var i = this.length - 1; i >= 0; i--)
r = r.multiply(p).add(this[i]);

return r;
}

特に問題なさそうだが、
足し算のところに工夫の余地がある。
足し算のときにわざわざオブジェクトを生成せずに、
オブジェクトに加算すればよい。


poly.prototype.add_assign = poly_add_assign;

// 加算代入
function poly_add_assign(p) {
var length = this.length;
if(typeof p == "number") {
if(length > 0)
this[0] += p;
else
this[0] = p;
}
else if(p instanceof poly) {
var p_length = p.length;
if(length > p_length) {
var i;
for(i = 0; i < p_length; i++)
this[i] += p[i];
}
...
}
else
throw("unsupported argument in poly::add");

return this;
}

こうしておいて、


// 合成
function poly_synthesize(p) {
if(!(p instanceof poly))
throw("unsupported argument in poly::synthesize");

var r = [ ];
for(var i = this.length - 1; i >= 0; i--) {
r = r.multiply(p);
r.add_assign(this[i]);
}

return r;
}

これで、4140ms→3266msとなった。


さらに、減算代入も同様に定義して、
積分の最後の引き算


return [r12].subtract(r11);

を、


return [r12].subtract_assign(r11);

としたら、2938msとなった。