Reputation: 1216
Relevant code
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");
Relevant output
Size of objectArray = 4000024 bytes
Size of intArray = 4000024 bytes
Size of objectMatrix = 17600024 bytes
Size of intMatrix = 10400024 bytes
If instead of 1D (number of cols=1), I have 2D (number of cols > 1), the object matrix takes more space.
Can someone explain the reason?
Edit: Added another case with just one row
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");
Output
Size of objectArray = 64 bytes
Size of intArray = 64 bytes
Size of objectMatrix = 72 bytes
Size of intMatrix = 64 bytes
Upvotes: 3
Views: 585
Reputation: 370
The size of the reference inside of the object array depends on many factors (32 bit vs 64 bit) or if you are in 64 bit are you running compressedOOPs? Since I typically work in a 64 bit environment I would always expect the Object[] to occupy more memory. On the other hand an int in Java is defined as a 32bit value, so with an int[] you are going to have 32 bits used for each value plus some overhead for the array object itself.
Upvotes: 1