[英]How much space does BigInteger use?
BigInteger對象一般使用多少字節的內存?
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;
下面這個帖子:
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字節。
在64位JVM上使用VisualVM保留大小,這里有一些具體的數字:
為了比較:
所以BigInteger
至少比Long
3倍,比long
10倍。 所以只有在真正需要時才使用BigInteger!
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 。
它可以表示任何大小的整數。 為您的應用程序分配的內存是限制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.