How many bytes of memory does a BigInteger object use in general ?
BigInteger internally uses an int[]
to represent the huge numbers you use.
Thus it really depends on the size of the number you store in it. The int[]
will grow if the current number doesn't fit in dynamically.
To get the number of bytes your BigInteger
instance currently uses, you can make use of the Instrumentation
interface, especially getObjectSize(Object)
.
import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
To convince yourself, take a look at the source code, where it says:
/**
* The magnitude of this BigInteger, in <i>big-endian</i> order: the
* zeroth element of this array is the most-significant int of the
* magnitude. The magnitude must be "minimal" in that the most-significant
* int ({@code mag[0]}) must be non-zero. This is necessary to
* ensure that there is exactly one representation for each BigInteger
* value. Note that this implies that the BigInteger zero has a
* zero-length mag array.
*/
final int[] mag;