<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 |
---|---|
Multiply using Decimal.js | |
Multiply using native numbers | |
Multiply using numerical strings parsed with Number | |
Multiply using numerical strings parsed with parseFloat |
Test name | Executions per second |
---|---|
Multiply using Decimal.js | 2292.6 Ops/sec |
Multiply using native numbers | 3018357.2 Ops/sec |
Multiply using numerical strings parsed with Number | 570904.3 Ops/sec |
Multiply using numerical strings parsed with parseFloat | 24404.6 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
What's being tested?
MeasureThat.net is running JavaScript microbenchmarks to compare the performance of different approaches for performing arithmetic operations on decimal numbers. Specifically, it's testing four scenarios:
Options compared
The benchmark compares the performance of each approach in three test cases:
These tests are similar, but use slightly different approaches to convert string representations to numbers.
Pros and cons
Here's a brief summary of the pros and cons for each approach:
Library: Decimal.js
Decimal.js is a library that provides precise floating-point arithmetic, allowing developers to perform calculations with decimal numbers without worrying about rounding errors. It's useful in applications where accuracy is crucial, such as financial transactions, scientific simulations, or data analysis.
Other considerations
When choosing an approach for decimal arithmetic, consider the following factors:
Alternatives
Other alternatives for decimal arithmetic in JavaScript include:
Keep in mind that these alternatives might have different requirements, dependencies, or trade-offs compared to using a dedicated library like Decimal.js or relying on native numbers and parseFloat().