gpt4 book ai didi

java - 如何计算 LinkedList 的实际大小(以字节为单位)?

转载 作者:行者123 更新时间:2023-11-30 08:46:04 26 4
gpt4 key购买 nike

有什么方法可以计算 LinkedList 的实际大小(以字节为单位)?

假设我有这个列表:

final LinkedList<String> strings = new LinkedList<>();
final SecureRandom random = new SecureRandom();
for (int i = 0; i < 600; i++) {
final String e = new BigInteger(130, random).toString(32);
strings.add(e);
}

如何计算堆中有多少字节占用此 LinkedList。 不仅是这600个字符串,还有LinkedList的所有链接和其他元数据


我最终使用 Runtime.getRuntime() 提出了建议的方法。

用上面提到的方法生成字符串(每个长度为 32 的字符串)以字节为单位给我这个值:

Length      Size in bytes       L/S
--- --- ---
5 0 0
10 0 0
25 102.4036458333 0.244131932966
50 102.4036458333 0.488263865931
125 0 0
250 102.4036458333 2.44131932966
625 614.41796875 1.01722285445
1250 1843.2291666667 0.678157671659
3125 5632.1041666667 0.5548547945
6250 11162.2265625 0.55992413028
15625 500.9817708333 31.1887595711
31250 29318.5390625 1.06587848506
78125 30802.51171875 2.53631913895
156250 117437.975260417 1.33048955973
390625 84691.7486979167 4.61231472966
781250 125415.6875 6.22928451435
1953125 309488.9921875 6.31080603609
3906250 509038.018229167 7.67378832251

enter image description here

最佳答案

写一个像这样的方法:

private long getMemoryUsage(){
long totalMem= Runtime.getRuntime().totalMemory();
long freeMem = Runtime.getRuntime().freeMemory();
return (totalMem- freeMem );
}

并在创建和填充列表之前和之后调用此方法。

long startMemory = getMemoryUsage();
final LinkedList<String> strings = new LinkedList<>();
final SecureRandom random = new SecureRandom();
for (int i = 0; i < 600; i++) {
final String e = new BigInteger(130, random).toString(32);
strings.add(e);
}
long endMemory = getMemoryUsage();

int size = (endMemory - startMemory )

但它永远不会给你一个准确的结果

关于java - 如何计算 LinkedList<String> 的实际大小(以字节为单位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33061980/

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