Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options to speed up Math.pow() in JavaScript?

I have some code which requires many Math.pow() function calls per second. In testing it seems to be a very large bottleneck to the performance of the code.

The results don't need to be precise - an accuracy of anywhere upwards of 85% should done fine - but my question would be is there any way I can somehow speed these calculations up? Maybe at the cost of some precision?

Edit: these calculations are very unlikely to repeat so a cache wouldn't work.

like image 577
user11406 Avatar asked Aug 15 '26 13:08

user11406


1 Answers

at the cost of some precision

How much loss of precision? If you only need correct answers by a factor of 2, you could use bitwise manipulation.

function pow2(n) {
  return 2 << (n-1);
}

console.log(pow2(n) === Math.pow(2, n));

The Number constructor (including number literals) use only floating point numbers. This function converts the floats to 32-bit integers as described here.

Otherwise, I doubt you'll be able to beat the optimized native implementation of Math.pow.

like image 127
twinlakes Avatar answered Aug 18 '26 04:08

twinlakes