<!--script src="https://raw.githubusercontent.com/iriscouch/bigdecimal.js/v0.6.1/lib/bigdecimal.js"></script-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/9.0.1/bignumber.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/big.js/6.0.3/big.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.2.1/decimal.min.js"></script>
<!--script src="https://raw.githubusercontent.com/infusion/Fraction.js/v4.0.12/fraction.min.js"></script-->
var a = 0.1;
var b = 0.2;
Math.fround((a + b) * b).toString();
var a = new Decimal("0.1");
var b = new Decimal("0.2");
a.plus(b).times(b).toString();
var a = new Big("0.1");
var b = new Big("0.2");
a.plus(b).mul(b).toString();
var a = new BigNumber("0.1");
var b = new BigNumber("0.2");
a.plus(b).multipliedBy(b).toString();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native | |
decimal.js | |
big.js | |
bignumber.js |
Test name | Executions per second |
---|---|
Native | 5222974.5 Ops/sec |
decimal.js | 417604.1 Ops/sec |
big.js | 629759.3 Ops/sec |
bignumber.js | 368546.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark compares the performance of three libraries for decimal arithmetic: big.js, bignumber.js, and decimal.js. The test cases focus on the fround()
function, which converts a number to a fixed-point representation, and the plus()
, times()
, and toString()
methods for performing basic arithmetic operations.
Libraries and Their Purpose
Test Cases
The benchmark consists of four test cases, each using one of the libraries:
Math.fround()
function, which converts a number to a fixed-point representation.Decimal
class from decimal.js to perform arithmetic operations.Big
class from big.js to perform arithmetic operations.BigNumber
class from bignumber.js to perform arithmetic operations.Comparison of Approaches
Each library has its pros and cons:
Math.fround()
function is simple and efficient, but it may lose precision due to rounding errors. It's a good choice when precision is not critical.Considerations
When choosing a library, consider the following factors:
Other Alternatives
Besides the three libraries mentioned above, there are other options available:
In summary, the choice of library depends on your specific requirements, performance needs, and ease of use preferences. By understanding the strengths and weaknesses of each library, you can make an informed decision for your project.