These days I had to do some monetary calculations in Java. This reminded me again about primitive double type and that it is absolutely the worst thing you can use when dealing with money. As you know, primitive double don't necessarily give you the right value, only the value that can be stored in a binary number format (any decimal number is represented by an approximated value). Whilst, java.math.BigDecimal gives you the required precision, its performance is very poor comparable to primitive types.
Below are few simple tests that are measuring BigDecimal performance based on a simple computation x2 + y2 which is performed in a loop 250000 times. In order to exclude the JVM warm-up cost, each test was executed 10 times. The execution time was calculated as average of all executions except first execution (exec2 + exec3 + … + exec10) / 9.
Read More »