使用了多少字节?

时间:2014-11-05 22:24:15

标签: java memory byte

考虑一个MysteryBox类型的对象,它存储N个boolean类型的项目 在长度为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)
    ...
}

使用多少字节作为N(64位内存成本模型)的函数?我的回答是否正确?

1 个答案:

答案 0 :(得分:0)

让我们通过实验发现!

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;
            }
        }
    }
}

结果:相对于N,每个MysteryBox的内存使用非常线性(r ^ 2舍入为1)。以字节为单位的内存使用量由1.0052N + 33.84给出。因此,显然每个布尔值占用大约一个字节,所有剩余的开销都适合大约34个字节。我将留给你推测如何分配开销。