<div id="num"></div>
var el = document.getElementById('num');
var decimal = 30.0;
for (var i = 0; i < 10000; i++) {
decimal += (i / 1000);
el.innerHTML = parseInt(decimal, 10);
}
var decimal = 30.0;
for (var i = 0; i < 10000; i++) {
decimal += (i / 1000);
el.innerHTML = decimal.toFixed();
}
var decimal = 30.0;
for (var i = 0; i < 10000; i++) {
decimal += (i / 1000);
el.innerHTML = ~~decimal;
}
var decimal = 30.0;
for (var i = 0; i < 10000; i++) {
decimal += (i / 1000);
el.innerHTML = decimal | 0;
}
var decimal = 30.0;
for (var i = 0; i < 10000; i++) {
decimal += (i / 1000);
el.innerHTML = Math.round(decimal);
}
var decimal = 30.0;
for (var i = 0; i < 10000; i++) {
decimal += (i / 1000);
el.innerHTML = Math.trunc(decimal);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
parseInt | |
toFixed | |
Tilde | |
Bitwise | |
Math.round | |
Math.trunc |
Test name | Executions per second |
---|---|
parseInt | 34.9 Ops/sec |
toFixed | 31.0 Ops/sec |
Tilde | 31.1 Ops/sec |
Bitwise | 35.4 Ops/sec |
Math.round | 35.5 Ops/sec |
Math.trunc | 35.3 Ops/sec |
Let's break down the benchmark and explain what is being tested.
What is being tested?
The benchmark is comparing four different methods to format or manipulate decimal numbers:
parseInt
toFixed
decimal | 0
)Math.round
and Math.trunc
The test case is creating a decimal number and repeatedly adding a small increment to it, updating an HTML element with the current value using each of these methods.
Options compared
parseInt
: converts the decimal number to an integertoFixed
: formats the decimal number as a fixed-point string (e.g., "30.0")~~
): uses the bitwise NOT operator to round down to the nearest whole numberdecimal | 0
): uses the bitwise AND operator with 0 to truncate the decimal partMath.round
: rounds the decimal number to the nearest integerMath.trunc
: truncates the decimal number to the nearest whole number (similar to "Tilde" but using a built-in function)Pros and cons of each approach
parseInt
: simple, fast, but may lose precision due to rounding errorstoFixed
: more precise than parseInt
, but can be slower due to string formatting overhead~~
): fast, but can produce unexpected results if the input is not an integerdecimal | 0
): very fast, but may be less readable and more prone to errorsMath.round
: more precise than parseInt
, but still rounds downMath.trunc
: similar to "Tilde" but using a built-in function, which can be faster and more reliableOther considerations
~~
as a shorthand for rounding down is also uncommon. It's better to use Math.trunc
or Math.round
instead.Library
None mentioned in this benchmark. However, note that some browsers (like Chrome) have built-in functions like toFixed
and Math.round
/Math.trunc
, which can simplify the implementation.
Special JS feature/syntax
None explicitly mentioned in this benchmark.