我有一个小的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/