17

一般に、BigInteger オブジェクトは何バイトのメモリを使用しますか?

4

4 に答える 4

16

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);
    }
}

自分を納得させるために、ソースコードを見てください。そこには次のように書かれています。

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

JVM 64 ビットで VisualVM 保持サイズを使用する場合の具体的な数値を次に示します。

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

比較のために:

  • Long (ラッパー クラス) = 24B (ただし、Long は 18 ~ 19 桁に制限されます)
  • long (プリミティブ) = 8B

したがってBigInteger、 は少なくとも の 3 倍、 のLong10 倍重いです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 に答える