<script src='https://cdn.jsdelivr.net/npm/decimal.js-light@2.5.0/decimal.min.js'></script>
var x = 5.236;
for (var i = 0; i < 1000; i++) {
Decimal('0.00253452345').plus(Decimal('0.042234'))
}
for (var i = 0; i < 1000; i++) {
0.00253452345 + 0.042234
}
for (var i = 0; i < 1000; i++) {
Number("0.00253452345") + Number("0.042234")
}
for (var i = 0; i < 1000; i++) {
parseFloat("0.00253452345") + parseFloat("0.042234")
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Add using Decimal.js | |
Add using native numbers | |
Add using numerical strings parsed with Number | |
Add using numerical strings parsed with parseFloat |
Test name | Executions per second |
---|---|
Add using Decimal.js | 1242.9 Ops/sec |
Add using native numbers | 3002465.0 Ops/sec |
Add using numerical strings parsed with Number | 7665.2 Ops/sec |
Add using numerical strings parsed with parseFloat | 5149.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
The provided benchmark compares the performance of four approaches for adding decimal numbers:
Number()
constructor.Let's analyze each approach:
Decimal.js
Pros:
Cons:
Native JS
Pros:
Cons:
Number()
Pros:
Cons:
parseFloat
Pros:
Number()
, but with the added benefit of being able to handle strings that represent floating-point numbers (e.g., 42.234
).Cons:
Number()
.The benchmark compares these approaches by measuring the execution time of each addition operation (with different decimal strings) using four different browsers. The results show that:
Number()
and parseFloat
have similar performance, but with limited precision.Other alternatives to consider:
bcadd
, bcmul
) that support arbitrary-precision arithmetic. These functions are often more efficient than libraries like Decimal.js and Big.js.When choosing an approach, consider the specific requirements of your application, such as precision, performance, and simplicity. If you need high precision, use a library like Decimal.js or Big.js. For fast execution without high precision, use native JavaScript operations.