[英]How to compute actual size of LinkedList<String> in bytes?
有什么方法可以計算 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 個 Strings ,還有 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
我認為您可以使用Runtime.totalMemory()
和Runtime.freeMemory()
來計算它1 。 另外,我更喜歡對接口進行編程。 就像是,
Runtime rt = Runtime.getRuntime();
long heapStart = rt.totalMemory() - rt.freeMemory();
final List<String> strings = new LinkedList<>();
final Random random = new SecureRandom();
for (int i = 0; i < 600; i++) {
final String e = new BigInteger(130, random).toString(32);
strings.add(e);
}
long heapEnd = rt.totalMemory() - rt.freeMemory();
System.out.printf("Used %d bytes%n", heapEnd - heapStart);
寫一個方法,如:
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 )
但它永遠不會給你一個確切的結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.