17

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

4

4 回答 4

16

BigInteger 在内部使用 anint[]来表示您使用的巨大数字。因此,它实际上取决于您存储在其中的数字的大小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);
    }
}

为了说服自己,请查看源代码,其中显示:

/**
 * 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;
于 2013-03-08T19:00:51.367 回答
9

这篇文章之后:

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字节。

于 2013-03-08T19:12:55.610 回答
3

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

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

为了比较:

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

所以BigInteger至少比 a 重 3 倍,比 aLong重 10 倍long。因此,仅在您真正需要时才使用 BigInteger!

于 2018-12-20T14:45:34.813 回答
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

于 2013-03-08T19:20:37.517 回答