tools4j / decimal4j

Java library for fast fixed-point arithmetic based on longs with support for up to 18 decimal places.
decimal4j.org
MIT License
156 stars 17 forks source link

nativeDecimal vs MutableDecimal #11

Closed jbycraft closed 7 years ago

jbycraft commented 7 years ago

Really hoping I can retire BigDecimal with this library =)

So question regarding the benchmarks. Obviously the nativeDecimal is the best performing version, however it seems like this is testing the underlying API that supports the mutable and immutbale decimals, correct?

I'm looking to understand if there is specific conditions under which the nativeDecimal approach can be implemented to achieve the best performance, beyond what is offered in MutableDecimal.

In my case I could set a precision of 15 across the board - so I started making a class that held a long, the DecimalArithmetic and the Scale, but began to wonder if this is not just the MutableDecimal implementation. I have some nested classes static method that do some fun things like chain operations i.e. calculate(Add(val), Subtract(val),Add(val),Multiply(val)), but in the end, I will accept any syntax that gives the performance.

So can you clarify the gap between the Decimal Arithmetic API and MutableDecimal? Thank you!

terzerm commented 7 years ago

Hi

You are right the native API is used for both the mutable and the immutable decimal implementations. Native benchmarks test the API directly, i.e. no objects are involved. This is also the main reason why you see better performance: e.g. no member variables need to be read and written.

If you are trying to implement an own decimal with precision 15 I recommend you use MutableDecimal15f instead. I doubt you would achieve better performance than that. Also keep in mind that the max value with precision 15 is less than 10000!

Please also note that BigDecimal is actually very well engineered and performs quite well, which is also visible when you compare the divide operation of decimal4j with BigDecimal (mostly equivalent performance). This library beats the performance of BigDecimal for simple operations (add, subtract) and is somewhat faster for multiply. It is also better when you are converting values to strings or doubles.

Good luck with your implementation!