BigInteger使用多少空间?

时间:2013-03-08 18:56:23

标签: java biginteger

BigInteger对象通常使用多少字节的内存?

5 个答案:

答案 0 :(得分:14)

BigInteger在内部使用int[]来表示您使用的巨大数字。 因此,它确实取决于您存储在其中的数字的大小。如果当前数字不适合动态,int[]将会增长。

要获取BigInteger实例当前使用的字节数,您可以使用Instrumentation界面,尤其是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);
    }
}

要说服自己,请查看source code,其中包含:

/**
 * 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;

答案 1 :(得分:6)

关注this帖子:

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

总共20个字节+整数数组。长度为N的整数数组的大小为4N + 24(数组开销+ 4字节/整数)。

总共会产生4N + 44个字节,具体取决于你的数字有多大。不要忘记对象的引用也使用内存。

编辑:作为对象开销的16个额外字节,使其达到4N + 60字节。为此添加填充(每个对象使用8个字节的倍数),我们得到额外的4个字节。

这导致 4N + 64 字节。

答案 2 :(得分:2)

在64位JVM上使用VisualVM保留大小,这是一些具体数字:

  • BigInteger 1 位= 70B (例如:new BigInteger(“ 9”))
  • BigInteger 20 位= 80B (例如:new BigInteger(“ 12345678901234567890”))
  • BigInteger 100 位= 112B

为了进行比较:

  • (包装类)= 24B (但长限制为18-19位数字)
  • (原始)= 8B

因此,BigIntegerLong重至少3倍,比long重10倍。因此,仅在确实需要时才使用BigInteger!

答案 3 :(得分:1)

Java对象大小取决于其字段。这些是BigInteger字段

final int signum;
final int[] mag;
private int bitCount;
private int bitLength;
private int lowestSetBit;
private int firstNonzeroIntNum;

我们可以将BigInteger实例的大小计算为

8 + 4 + (12 + mag.length * 4) + 4 + 4 + 4 + 4  ~= 40 + mag.length * 4 

http://www.javamex.com/tutorials/memory/object_memory_usage.shtml

答案 4 :(得分:-4)

它可以表示任何大小的整数。为您的应用程序分配的内存是限制。

相关问题