var width = 480;
var halfWidth = width >> 1;
var invertedHalfWidth = 1 / halfWidth;
var xPos = Math.random() * width;
var xQuadLeft = xPos < halfWidth ? 0 : 1;
var xPos = Math.random() * width;
var diff = xPos ^ halfWidth;
diff |= diff >> 1;
diff |= diff >> 2;
diff |= diff >> 4;
diff |= diff >> 8;
diff |= diff >> 16;
diff &= ~(diff >> 1) | 0x80000000;
diff &= (xPos ^ 0x80000000) & (halfWidth ^ 0x7fffffff);
var xQuad = !!diff;
var xPos = Math.random() * width;
var xQuad = xPos ^ halfWidth && (
!(halfWidth ^ 0) ||
( (xPos / halfWidth) | 0 )
);
var xPos = Math.random() * width;
var xQuad = xPos == width ? 1 : ( ( xPos * invertedHalfWidth ) | 0 );
var xPos = Math.random() * width;
var xQuad = xPos == width ? 1 : ~~( xPos * invertedHalfWidth );
var xPos = Math.random() * width;
var xQuad = ~~( xPos * invertedHalfWidth );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Conditional comparison | |
Bitwise comparison | |
Other test | |
Other test 2 | |
Other test 3 | |
Other test 4 |
Test name | Executions per second |
---|---|
Conditional comparison | 3606998.0 Ops/sec |
Bitwise comparison | 2846421.8 Ops/sec |
Other test | 2385217.0 Ops/sec |
Other test 2 | 2833298.5 Ops/sec |
Other test 3 | 2834286.8 Ops/sec |
Other test 4 | 3475396.2 Ops/sec |
What is being tested?
The provided benchmark tests the performance of different approaches for comparing numbers in JavaScript. The tests are designed to measure the time it takes for the browser to execute each comparison.
Options compared:
xPos < halfWidth ? 0 : 1
xPos
is less than halfWidth
.^
, |
, &
) to compare xPos
and halfWidth
. Specifically, it uses the XOR operator (^
) to find the difference between the two values.xPos == width
xPos
with width
using a floating-point equality check.~~(xPos * invertedHalfWidth)
xPos
to the nearest integer by using the unary negation operator (~
) after multiplying it with invertedHalfWidth
.Pros and cons of each approach:
Other considerations:
Latest benchmark result:
The latest benchmark results show that the bitwise comparison approach is generally faster than the other options, while the floating-point comparison and integer comparison (rounding) approaches are similar in speed.
Conclusion:
This benchmark provides a useful comparison of different approaches for comparing numbers in JavaScript. By testing these different approaches, developers can gain insight into the performance characteristics of each method and make informed decisions about which approach to use depending on their specific needs and requirements.