Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BigDecimal memory usage?

Tags:

Is there a guideline for estimating the amount of memory consumed by a BigDecimal?

Looking for something similar to these guidelines for estimating String memory usage.

like image 581
Marcus Leon Avatar asked Mar 23 '10 15:03

Marcus Leon


People also ask

How much space does a BigDecimal take?

Assuming you don't call . toString() , it will remain zero bytes. Hence BigDecimal is (8+4+4)=16 bytes + BigInteger . BigInteger itself is 4+4+4+4+4=20 bytes + mag .

How big is a BigDecimal?

A BigDecimal consists of a random precision integer unscaled value and a 32-bit integer scale.

What is the limit of BigDecimal in Java?

The largest value BigDecimal can represent requires 8 GB of memory.

How much slower is BigDecimal than double?

According to my own benchmarking for my specific use case it's 10 - 20x slower than double (much better than 1000x) - basically for addition / multiplication.


1 Answers

If you look at the fields in the source for BigDecimal there is:

BigDecimal:   long intCompact +8 bytes   int precision +4 bytes   int scale +4 bytes   String stringCache +?   BigInteger intVal +?  BigInteger:   int bitCount +4 bytes   int bitLength +4 bytes   int firstNonzeroIntNum +4 bytes   int lowestSetBit +4 bytes   int signum +4 bytes   int[] mag +? 

The comment for stringCache says

Used to store the canonical string representation, if computed.

Assuming you don't call .toString(), it will remain zero bytes. Hence BigDecimal is (8+4+4)=16 bytes + BigInteger.

BigInteger itself is 4+4+4+4+4=20 bytes + mag.

20+16 gives total of 36 bytes plus the magnitude, which is always the minimum number of bits necessary to represent the full integer. For a number n it will need log2(n) bits, which can be converted to ints. You should be using about:

36 + Ceiling(log2(n)/8.0) bytes 

(note this doesn't include any of the other object descriptor overhead as your example link for strings does, but it should give you a good general idea.)

like image 135
M. Jessup Avatar answered Sep 24 '22 10:09

M. Jessup