Skip to content

Instantly share code, notes, and snippets.

@bga
Created October 15, 2010 17:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bga/628591 to your computer and use it in GitHub Desktop.
Save bga/628591 to your computer and use it in GitHub Desktop.
// http://en.wikipedia.org/wiki/Fast_inverse_square_root
/*
Discovering old well known algorithm speed in js.
*/
var _invSqrtL = (function()
{
var u32Array = new Uint32Array(1), f32Array = new Float32Array(u32Array.buffer);
return function(x)
{
f32Array[0] = x;
u32Array[0] = 0x5f3759df - (u32Array[0] >> 1);
var y = f32Array[0];
return y * (1.5 - 0.5 * x * y * y);
};
})();
_speedTest(
[
function(n)
{
// _invSqrtL inlined manualy
var u32Array = new Uint32Array(1), f32Array = new Float32Array(u32Array.buffer);
var s = 0;
var i = n; while(i--)
{
f32Array[0] = i;
u32Array[0] = 0x5f3759df - (u32Array[0] >> 1);
var y = f32Array[0];
s += y * (1.5 - 0.5 * i * y * y);
}
},
function(n)
{
var _sqrt = Math.sqrt; // caching for best speed
var s = 0;
var i = n; while(i--)
{
s += 1/_sqrt(i);
}
}
],
10000
);
/*
chrome8
0: 820 ms
1: 411 ms
ff4
0: 132 ms
1: 284 ms
*/
/*
Yes it faster in js too, but only in one browser and requires special api.
Anyway nice.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment