如何计算LinkedList <string>的实际大小(以字节为单位)?

时间:2015-10-11 05:47:18

标签: java list

是否有任何方法可以以字节计算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

2 个答案:

答案 0 :(得分:1)

我认为您可以使用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);

1 我不确定这种方法有多准确。您可能最好使用分析器(例如visualvmChronon

答案 1 :(得分:1)

编写如下方法:

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 ) 

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