2017-12-11 2 views
5

コード次のオブジェクト配列の計算メモリサイズは、私の知る限り、から構成され、予想通り「24バイトを使用する」を与える場合:のJavaオブジェクトのアレイサイズ

4bytes(element pointer)+16bytes(object header)+4bytes(element space) = 24bytes

// with JVM argument -XX:-UseTLAB 
public static void main(String[] args) { 
    long size = memoryUsed(); 
    Object[] o = new Object[]{1}; 
    //Object[] o = new Object[]{1L}; 
    size = memoryUsed() - size; 
    System.out.printf("used %,d bytes%n", size); 
    //Output: used 24 bytes 
} 

public static long memoryUsed() { 
    return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); 
} 

要素タイプがLong(1L)に変更された場合、結果は混乱します。ほとんどの場合、「9,264バイト使用」、誰でも私を啓発するのに役立つでしょうか?この2つの要素型の間のメモリ割り当ての違いは何ですか? JOLと呼ばれるそのための専用ツールがあるよう

// with JVM argument -XX:-UseTLAB 
public static void main(String[] args) { 
    long size = memoryUsed(); 
    //Object[] o = new Object[]{1}; 
    Object[] o = new Object[]{1L}; 
    size = memoryUsed() - size; 
    System.out.printf("used %,d bytes%n", size); 
    //Output: used 9,264 bytes 
} 
+1

恐らく、JVMは、あなたが期待するよりも多くのメモリを消費する追加のクラス( 'Long'や内部クラス' Long.LongCache'など)をロードする必要があります。 –

+0

[Javaでは、オブジェクトのサイズを判断する最善の方法は何ですか?](https://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to -determine-the-object-of-object) –

答えて

0

は、一般的にオブジェクトのサイズを計算するためのより良い方法があります。

あなたの考え方は完全に正しくありません。そのオブジェクトの合計サイズは40 bytesになります。このスペースはどこから来ているのを見てみましょう:

12 bytes headers (8 bytes + 4 bytes, since there are two headers) 

は、あなたはそれが16 bytes(8 + 8)だと思ったが、デフォルトでオンになってcompressed oopsオプションがあります。 -XX:-UseCompressedOopsで無効にすることができます。この場合、ヘッダーのサイズは16 bytesになります。

4 bytes size of the array (arrays have an int size that is stored in headers) 
4 bytes is the reference size of the Integer (1) 
4 bytes alignment (since objects are 8 bytes aligned - this is the trick behind CompressedOops btw) 

これまでのところ、アレイには24 bytesがあります。

は今、あなたはこのように、それはあまりにもオブジェクトで、その中に整数を格納します。

12 bytes headers 
4 bytes for the actual int value inside Integer 

したがって合計サイズが40 bytesです。

+0

この配列に格納されている整数がそのプリミティブ型であるため、余分な16バイトのオブジェクトヘッダを保存することができますか? –

+0

@鄭无护'それでは' Integer'になります。そのスペースを節約したい場合は、 'int []'として宣言する必要があります。 – Eugene

関連する問題