var i;
var r;
var v = 2 ** 16;
function test1() {
for (i = 0; i < 100000; ++i) {
r = Math.sqrt(v);
}
}
function test2() {
for (i = 0; i < 100000; ++i) {
r = Q_rsqrt(v) * v;
}
}
//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;
}
test1();
test2();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Math.sqrt | |
Quakes fast inverse sqrt. |
Test name | Executions per second |
---|---|
Math.sqrt | 28.5 Ops/sec |
Quakes fast inverse sqrt. | 6.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition JSON
The provided Benchmark Definition JSON represents a comparison between two functions: Math.sqrt
and a custom implementation of the fast inverse square root function (Q_rsqrt
). The Fast Sqrt0
benchmark is designed to measure the performance difference between these two approaches.
What is being tested?
The test cases are comparing the execution speed of:
Math.sqrt
: A built-in JavaScript function that calculates the square root of a given number.Q_rsqrt
: A custom implementation of the fast inverse square root function, which is based on an optimized algorithm from Wikipedia.Options being compared
The two options being compared are:
Math.sqrt
: The built-in JavaScript function.Q_rsqrt
: The custom implementation of the fast inverse square root function.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Math.sqrt
:Q_rsqrt
.Q_rsqrt
:Library and purpose
The Q_rsqrt
function uses a library-like approach by:
ArrayBuffer
to store the input value.new Uint32Array(buf)[0]
.This implementation is similar to how the fast inverse square root function works, but with a JavaScript twist.
Special JS feature or syntax
No special features or syntax are used in this benchmark.
Other alternatives
If you were to implement your own Q_rsqrt
function without using an array buffer-like approach, you could use:
However, these alternatives might not be as efficient as using an optimized library-like approach or a built-in function like Math.sqrt
.
Keep in mind that this benchmark is designed to compare the performance of two specific functions, and the results may vary depending on your specific use case and JavaScript environment.