Which is Faster? Math.trunc, or the Bitwise OR trick?
June 20, 2019
Math.truncor the Bitwise OR trick?
Math.trunc was introduced as an easy way to convert a
floating point number to an integer representation.
Prior to this, it was popular to actually use the bitwise-OR with 0 trick to
actually simulate this effect. For example:
a = 1.123123 would have been:
a =| 0
Which would have given back
a = 1.
This test aims to see which is actually faster. Should we use
Math.trunc, or bitwise-OR with 0?
32_000_000 random floating point numbers in the ranges of [0, 100) are initially generated.
The benchmark starts when these numbers are populated in an array and measures the time it takes convert all floating point numbers into a new array of integers.
10 tests are run for each method, and the sum of the times are given.
Turns out, they're pretty close.
Note: These tests block the UI.
JS code can be found here float2int.js.