How many bytes are used?
Consider an object of type MysteryBox, which stores N elements of type boolean in an element of the array [] of length N.
public class MysteryBox { // 16B (object overhead)
private int N; // 4B (int)
private boolean[] items; // 8B (reference to array)
// 24B (header of array)
// N (boolean array of size N)
// 4B for padding
// 17N (boolean objects, 16B of object metadata, 1B of data equivalent to 1 boolean)
...
}
how many bytes are used as function N (64-bit memory cost model)? Is my answer correct?
+3
source to share
1 answer
Find out experimentally!
public static void main(String[] args)
{
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); //This might cause a little bit of error
for(int N=1400;N<5000;N+=100) //this is on the stack, so it shouldn't affect us
{
int[] reserved = new int[1000]; //we'll clear this later
MysteryBox box = new MysteryBox(N);
int count = 1;
while(true)
{
try
{
MysteryBox temp = new MysteryBox(N);
temp.next = box; //don't worry, this extra variable was subtracted out during analysis
box=temp;
count++;
}
catch(java.lang.OutOfMemoryError e)
{
reserved = null;
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
long maxMemory = heapUsage.getMax();
long usedMemory = heapUsage.getUsed();
System.out.println(N+ " : " + count + " : Memory Use :" + usedMemory + "/" + maxMemory + "");
break;
}
}
}
}
Result: The memory usage in the MysteryBox is extremely linear (r ^ 2 rounds up to 1) with respect to N. The memory usage in bytes is given by 1.0052N + 33.84. So, it is obvious that each boolean takes about one byte, and all the other overhead is about 34 bytes. I'll leave that to you to talk about the allocation of overhead.
0
source to share