Test name | Executions per second |
---|---|
Math.pow | 15862194.0 Ops/sec |
pow2 bitwise | 15572650.0 Ops/sec |
pow2 summ | 291965.8 Ops/sec |
pow2 multi | 10332326.0 Ops/sec |
pow (mult for loop) | 32333926.0 Ops/sec |
function powNaive(x, y) {
if (!y) return 1;
let tmp = x;
for (let i = 1; i < y; i++) {
tmp *= x;
}
return tmp;
}
// from https://codereview.stackexchange.com/a/217369
function pow2B(x, y) {
if (y < 2) { return y ? x : 1 }
if (y & 1) { return x * pow2B(x, y & 0x7FFFFFFE)}
const p = pow2B(x, y >> 1);
return p * p;
}
// other two functions from the same stackexchange post
function pow(x, y) {
if (!y) { return 1 }
let tmp = res = x;
for (let i = 1; i < y; i++) {
for (let j = 1; j < x; j++) { tmp += res }
res = tmp;
}
return res;
}
function pow2(x, y) {
if (!y) { return 1; }
if (y % 2) {
return x * pow2(x, y - 1);
}
const p = pow2(x, y/2);
return p * p;
}
var x = Math.pow(54,2);
var y = pow2B(54, 2)
var y = pow(54, 2)
var y = pow2(54, 2)
var y = powNaive(54, 2)