Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much space does BigInteger use?

How many bytes of memory does a BigInteger object use in general ?

like image 533
Nikunj Banka Avatar asked Mar 08 '13 18:03

Nikunj Banka


People also ask

Does BigInteger have a limit?

BigInteger has no cap on its max size (as large as the RAM on the computer can hold).

Is BigInteger bigger than long?

3. BigInteger Larger Than Long. MAX_VALUE. As we already know, the long data type is a 64-bit two's complement integer.

Is BigInteger slow Java?

The standard library BigInteger class in Java is known to be notoriously slow (at least for Java 7 and earlier, and I doubt Java 8 is any different).

Can BigInteger overflow?

Correct, BigInteger never overflows, it uses software operations and dynamic allocation to store arbitrarily sized numbers.


2 Answers

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;
like image 131
poitroae Avatar answered Oct 11 '22 14:10

poitroae


Following this post:

BigInteger:
  int bitCount +4 bytes
  int bitLength +4 bytes
  int firstNonzeroIntNum +4 bytes
  int lowestSetBit +4 bytes
  int signum +4 bytes
  int[] mag +?

That's a total of 20 bytes + the integer array. An integer array of length N has size 4N + 24 (Array overhead + 4 bytes/integer).

In total this makes 4N + 44 bytes, depending on how big your number is. Don't forget the reference to an object also uses memory.

Edit: 16 additional bytes as object overhead, brings it to 4N + 60 bytes. Adding padding to this (each object uses a multiple of 8 bytes) we get an additional 4 bytes.

This results in 4N + 64 bytes.

like image 45
Jeroen Vannevel Avatar answered Oct 11 '22 14:10

Jeroen Vannevel