java - ArrayList 使用意外的堆大小

标签 java arraylist

我有一个小的java测试类,只有一个成员变量..并且该变量是一个字符串。我有一个 ArrayList,我在其中添加了很多此类的对象。我发现使用的堆大约是我添加到其中的数据的 6 倍)。有什么方法可以优化这个或者使用 ArrayList 在这种情况下会出现问题。

代码:

public class  testheap
{
String          regionId;   

testheap(String s) {  
    this.regionId = s;
}


public static void main(String[] args) throws Exception
{

    ArrayList<testheap> regList = new ArrayList<testheap>(10000);

    System.out.println("just Before looping");
    printHeapSizes();
    //looping
    int i = 0;
    while (i++ < 2500000)   {
        if (i%500000 == 0) printHeapSizes();  // print heap sizes every 500000th iteration
        testheap reg = new testheap("abcd");
        regList.add(reg);
    }
    System.out.println("end of loop");
    printHeapSizes();
 public static void printHeapSizes() {
 long heapSize = Runtime.getRuntime().totalMemory(); 

    // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
    //long heapMaxSize = Runtime.getRuntime().maxMemory();

     // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
    long heapFreeSize = Runtime.getRuntime().freeMemory(); 
    long usedSize = heapSize - heapFreeSize;
    System.out.println("total:"+heapSize+" Freesize:"+heapFreeSize + "      USED:"+usedSize);

代码结束

最佳答案

您应该只考虑完整GC之后的大小。我建议您先执行 System.gc()。

我预计添加一个像这样的简单对象会使用大约 28 个字节。 4 个字节用于 ArrayList 中的引用,24 个字节用于 testheap 对象本身(16 字节 header 、4 字节用于引用和 4 字节用于填充)

字符串在第一个字符串之后不使用任何空格,因为它每次都会使用相同的对象。

如果您关心内存使用情况并且知道所需列表的大小,请从一开始就使用该大小。

List<TestHeap> regList = new ArrayList<TestHeap>(2500000);

关于java - ArrayList 使用意外的堆大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20289813/

相关文章:

Java如何在值更新时维护数组列表中扫描对象的顺序

java - 出现错误 : > Process 'command '/Library/Java/JavaVirtualMachines/jdk1. 8.0_77.jdk/Contents/Home/bin/java'' 以非零退出值 1 完成

java - 无法在 Mac 上加载 jar-with-dependencies

java - Android - 获取昵称和昵称类型

java - AH00052 : child pid 2453 exit signal Segmentation fault (11)

android - 无法解析方法 'super(android.content.context,int,int,java.util.arraylist<android.Bluetooth.Bluetoothdevices>)'

java - Apache Beam Flatten Iterable<String>

java - 如何将数组列表的内容放入对象中?

java - 多维数组列表配对

java - Android 应用程序中颜色名称的 RGB 值