2012-04-13 27 views
3

相關代碼的java爲什麼不同內存使用原語與在2D對象陣列

int row = 100000; 
int col = 18; 

Object[][] objectArray = new Object[row][1]; 
int[][] intArray = new int[row][1]; 

System.out.println("Size of objectArray = " + net.sourceforge.sizeof.SizeOf.deepSizeOf(objectArray) + " bytes"); 
System.out.println("Size of intArray  = " + net.sourceforge.sizeof.SizeOf.deepSizeOf(intArray) + " bytes"); 

Object[][] objectMatrix = new Object[row][col]; 
int[][] intMatrix = new int[row][col]; 

System.out.println("Size of objectMatrix = " + net.sourceforge.sizeof.SizeOf.deepSizeOf(objectMatrix) + " bytes"); 
System.out.println("Size of intMatrix = " + net.sourceforge.sizeof.SizeOf.deepSizeOf(intMatrix) + " bytes"); 

相關輸出

Size of objectArray = 4000024 bytes 
Size of intArray  = 4000024 bytes 
Size of objectMatrix = 17600024 bytes 
Size of intMatrix = 10400024 bytes 

如果不是1D(數COLS = 1),I具有2D(數1),對象矩陣需要更多的空間。

有人可以解釋原因嗎?

編輯:添加另一種情況下只用一個行

int row = 1; 
    int col = 2; 

    Object[][] objectArray = new Object[row][1]; 
    int[][] intArray = new int[row][1]; 

    System.out.println("Size of objectArray = " + net.sourceforge.sizeof.SizeOf.deepSizeOf(objectArray) + " bytes"); 
    System.out.println("Size of intArray  = " + net.sourceforge.sizeof.SizeOf.deepSizeOf(intArray) + " bytes"); 

    Object[][] objectMatrix = new Object[row][col]; 
    int[][] intMatrix = new int[row][col]; 

    System.out.println("Size of objectMatrix = " + net.sourceforge.sizeof.SizeOf.deepSizeOf(objectMatrix) + " bytes"); 
    System.out.println("Size of intMatrix = " + net.sourceforge.sizeof.SizeOf.deepSizeOf(intMatrix) + " bytes"); 

輸出

Size of objectArray = 64 bytes 
Size of intArray  = 64 bytes 
Size of objectMatrix = 72 bytes 
Size of intMatrix = 64 bytes 
+0

我想也許一個對象數組需要更多的空間。 (不知道爲什麼會這樣,但這是可能的,這取決於內部實現。) – 2012-04-13 18:02:09

+3

(當然,在完整的64位Java實現中,指針是整數的兩倍)。 – 2012-04-13 18:03:07

+0

(我不知道如何deepSizeOf在內部工作,但如果它以某種方式查看分配,則不能保證兩個相同的對象佔用相同的大小分配。) – 2012-04-13 18:05:34

回答

1

對象陣列的內部基準的大小取決於許多因素(32位和64位)或如果你在64位,你是否運行compressedOOPs?由於我通常在64位環境下工作,我總是期望Object []佔用更多內存。另一方面,Java中的int被定義爲一個32位的值,所以對於一個int [],你將有32位用於每個值加上一些數組對象本身的開銷。

相關問題