Last active
May 18, 2024 00:09
-
-
Save starfys/aaaee80838d0e013c27d to your computer and use it in GitHub Desktop.
Fast inverse square root in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Based on the fast inverse square root function | |
// https://en.wikipedia.org/wiki/Fast_inverse_square_root | |
// Some original comments preserved for humor value | |
// Designed to try to mimic the original as closely as possible | |
function Q_rsqrt(number) | |
{ | |
var i; | |
var x2, y; | |
const threehalfs = 1.5; | |
x2 = number * 0.5; | |
y = number; | |
//evil floating bit level hacking | |
var buf = new ArrayBuffer(4); | |
(new Float32Array(buf))[0] = number; | |
i = (new Uint32Array(buf))[0]; | |
i = (0x5f3759df - (i >> 1)); //What the fuck? | |
(new Uint32Array(buf))[0] = i; | |
y = (new Float32Array(buf))[0]; | |
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration | |
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed | |
return y; | |
} |
moving computation impl to native is better most of the time, that's why they introduced WASM.
@ingvardm Here's my take on it, fisr
seems to become faster in higher orders of magnitude of iterations.
const buffer = new ArrayBuffer(4);
const ui32 = new Uint32Array(buffer);
const f32 = new Float32Array(buffer);
function Q_rsqrt (number)
{
f32[0] = number;
ui32[0] = 0x5F3759DF - (ui32[0] >> 1);
const x = f32[0];
return x * (1.5 - 0.5 * x * x * number);
}
let qTotal = 0, sTotal = 0;
const iters = 999999999;
for (let i = 0; i < iters; ++i)
{
const s = Date.now();
Q_rsqrt(i + 1);
qTotal += Date.now() - s;
}
for (let i = 0; i < iters; ++i)
{
const s = Date.now();
(1 / Math.sqrt(i + 1));
sTotal += Date.now() - s;
}
console.log("Q_rsqrt:", qTotal); // Q_rsqrt: 34027
console.log("1 / Math.sqrt:", sTotal); // 1 / Math.sqrt: 34372
So, at least in terms of javascript, this seems to be a problem of theoretical vs practical time complexity. Q_rsqrt is probably faster per iteration, but the additional overhead of the buffers and such causes native implementations to be faster for most use cases. But if you do happen to be running a billion calls to inverse square root, you probably shouldn't be using naked javascript. As valen214 said, WASM is probably a better investment if you're chasing performance.
Additional speed can be obtained by:
- Converting
const
tolet
- Convert
function () {...}
to() => {...}
- Inline the assignment:
let x = f32[0] = number
- making sure you are in strict mode
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please, take a minute to try to understand the code before you post your reply, thank you.