var count = 1000;
for (var i = 0; i < count; i++) {
Math.trunc(12.34 * 10);
Math.trunc(567.89 * 10);
}
for (var i = 0; i < count; i++) {
Math.round(12.34 * 10);
Math.round(567.89 * 10);
}
for (var i = 0; i < count; i++) {
Math.floor(12.34 * 10);
Math.floor(567.89 * 10);
}
for (var i = 0; i < count; i++) {
parseFloat((12.34 * 10).toFixed());
parseFloat((567.89 * 10).toFixed());
}
for (var i = 0; i < count; i++) {
~~(12.34 * 10);
~~(567.89 * 10);
}
for (var i = 0; i < count; i++) {
(12.34 * 10 |0);
(567.89 * 10 |0);
}
for (var i = 0; i < count; i++) {
parseInt(12.34 * 10);
parseInt(567.89 * 10);
}
for (var i = 0; i < count; i++) {
parseInt(12.34 * 10, 10);
parseInt(567.89 * 10, 10);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
trunc | |
round | |
floor | |
parseFloat to int | |
~~ | |
|0 | |
parseInt | |
parseInt, 10 |
Test name | Executions per second |
---|---|
trunc | 3857105.2 Ops/sec |
round | 3845987.2 Ops/sec |
floor | 3858572.5 Ops/sec |
parseFloat to int | 11734.7 Ops/sec |
~~ | 3888677.5 Ops/sec |
|0 | 3912829.8 Ops/sec |
parseInt | 3732859.0 Ops/sec |
parseInt, 10 | 3873018.2 Ops/sec |
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks, providing insights into the performance of various functions in different browsers.
The benchmark being discussed uses six different functions to convert a floating-point number to an integer:
Math.trunc()
Math.round()
Math.floor()
parseFloat()
with .toFixed()
(which is essentially equivalent to parseInt()
with a radix of 10)|
) followed by 0
(which is equivalent to parseInt()
with a radix of 10)~~
) followed by the value itself (which is not a standard JavaScript function, but is used as an alternative in this benchmark)Let's break down each function and their pros and cons:
1. Math.trunc()
2. Math.round()
3. Math.floor()
Math.trunc()
, but may not be as efficient in some cases.4. parseFloat() with .toFixed()
.toFixed()
.5. |
followed by 0
0
.6. ~~ (bitwise NOT) with value itself
The results of the benchmark show that Math.trunc()
and |
followed by 0 are the fastest methods, while parseFloat()
with .toFixed()
is significantly slower. The order of performance is:
Math.trunc()
|
followed by 0Math.floor()
Math.round()
parseInt()
(with radix 10)parseFloat()
with .toFixed()
Note that the performance results may vary depending on the specific browser and system being used.