gpt4 book ai didi

java - 使用了多少字节?

转载 作者:行者123 更新时间:2023-12-02 04:52:19 24 4
gpt4 key购买 nike

考虑一个 MysteryBox 类型的对象,它存储 N 个 boolean 类型的项目在长度为 N 的数组 item[] 中。

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 位内存成本模型)的函数?我的回答正确吗?

最佳答案

让我们通过实验找出答案!

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

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

关于java - 使用了多少字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26768320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com