var i;
var r;
var v = 2 ** 16;
function test1() {
for (i = 0; i < 1000; ++i) {
r = Math.sqrt(v);
}
}
function test2() {
for (i = 0; i < 1000; ++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
const bytes = new ArrayBuffer(Float32Array.BYTES_PER_ELEMENT);
const floatView = new Float32Array(bytes);
const intView = new Uint32Array(bytes);
const threehalfs = 1.5;
function Q_rsqrt(number) {
const x2 = number * 0.5;
floatView[0] = number;
intView[0] = 0x5f3759df - (intView[0] >> 1);
let y = floatView[0];
y = y * (threehalfs - (x2 * y * y));
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 | 167047.0 Ops/sec |
Quakes fast inverse sqrt. | 63387.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition JSON
The provided Benchmark Definition JSON represents a comparison between two test cases: test1()
and test2()
, which measure the performance of calculating the square root of 2 using the built-in Math.sqrt()
function and the Quake's fast inverse square root algorithm, respectively.
Options Compared
Two options are compared:
Math.sqrt()
: This is the built-in JavaScript method for calculating the square root of a number.Q_rsqrt()
): This is a custom implementation of the inverse square root function, designed to be faster than the built-in Math.sqrt()
method.Pros and Cons
Here are some pros and cons of each approach:
Math.sqrt()
:Q_rsqrt()
):The Quake's fast inverse square root algorithm is designed to take advantage of the IEEE 754 floating-point representation and uses bitwise operations to calculate the inverse square root. While it provides better performance in certain scenarios, it also introduces additional complexity and may not be suitable for all use cases.
Library: Float32Array
The Quake's fast inverse square root algorithm uses the Float32Array
library to manipulate floating-point numbers. This library is part of the JavaScript standard library and provides an efficient way to work with 32-bit floating-point numbers.
Special JS Feature/Syntax
None are explicitly mentioned in the provided Benchmark Definition JSON, but it's worth noting that JavaScript has several features and syntax that can impact performance, such as:
Other Alternatives
If you're looking for alternative implementations of the square root function or want to explore other optimization techniques, here are a few options:
libm
(on Linux) or libc
(on Windows) can provide optimized implementations of mathematical functions, including square root calculations.