var x = 9876.54321
x = x << 0;
x = ~~(x)
x = Math.trunc(x)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Bitwise | |
~~ | |
Math.trunc |
Test name | Executions per second |
---|---|
Bitwise | 4694159.5 Ops/sec |
~~ | 4699844.0 Ops/sec |
Math.trunc | 2651746.2 Ops/sec |
I'll do my best to explain the provided benchmarking setup.
Benchmark Definition
The benchmark measures how quickly three different methods can truncate a decimal number to an integer:
<<
) to create a binary representation of the number, effectively moving the decimal point to zero.~~
operator, which is the unary minus operator followed by the integer division operator /
. This operator returns the largest integer less than or equal to the input value.Math.trunc()
function from the JavaScript Math library, which returns the largest integer less than or equal to the input value.The benchmark notes that Math.floor
should not be used for truncating negative numbers, as it rounds down instead of rounding towards zero.
Test Cases
The individual test cases are:
<<
) to truncate a decimal number.~~
operator to truncate a decimal number.Math.trunc()
function from the JavaScript Math library to truncate a decimal number.Library Usage
In this benchmark, no libraries are explicitly mentioned as being used by the tests. However, it's worth noting that the Math
library is being used in the Math.trunc()
function.
Special JS Features/Syntax
There is no special JS feature or syntax being tested in this benchmark. The operators and functions used are standard JavaScript syntax.
Other Alternatives
If you were to write a similar benchmark, you might consider using alternative methods for truncating decimal numbers, such as:
Number.EPSILON
for relative error)Pros and Cons
Here are some pros and cons of each method:
Benchmark Considerations
When creating a benchmark like this, consider factors such as:
Keep in mind that benchmarks should aim to accurately measure performance under representative usage scenarios.