What is the memory size of an ArrayList in Java

丶灬走出姿态 提交于 2019-12-01 16:54:57
Daniel DiPaolo

You can use something like Runtime.getRuntime().totalMemory() and its counterpart Runtime.getRuntime().freeMemory() to get an educated guess, but that doesn't account for objects that are GC'ed between calls.

bestsss

It's the capacity of the java.util.ArrayList multiplied by the reference size (4 bytes on 32bit, 8bytes on 64bit) + [Object header + one int and one references].

The capacity is different (always >=) than the size but you want to make 'em equal, call trimToSize()

Technically speaking the ArrayList has an Object[] where it stores the data.

This is what a memory profiler is for. It will tell you for your platform. The minimum size for an empty ArrayList is 64-bytes. It is highly likely you don't need to know this unless you have 100K elements or more.

You can brute force calculate it if you know the content distribution of the objects.

However, the most precise method I can think of is to look at it in a profiler. There are free tools out there, some that come with the JDK. However, the best tool I've used is Yourkit. That doesn't mean it's the only solution, just my favorite.

You may have to use a profiler like the one available in Netbeans that will show you the memory consumption of our program and can give you some details about each object.

The answer is, it depends on how you measure. If you asked me the size of an ArrayList I would give you the shallow size. That is to say, an ArrayList consists of an array of references and an integer indicating the number of contained elements. If you wanted to know the size it is quite simply 4 + *array.length.

If you want to know the size of the ArrayList and all contained elements then there are some heap analyzers that can figure this out. I believe YourKit is one of them.

The memory usage of java depends of the JVM implementation. The only real method to determine the memory usage of an instance I know is to use an Java 5 instrumentation agent. There is a little tutorial to do so.

The way an ArrayList works is that it simply contains an array of a certain size (which can be specified in the constructor, I believe 10 is the default?). Whenever the number of elements becomes too large for the internal array, the size of the internal array is doubled. So you need to multiply the size of the object by the size of the internal array.

Source: http://uttesh.blogspot.com/2015/04/get-byte-or-memory-size-of.html

public static long getBytesFromList(List list) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(baos);
    out.writeObject(list);
    out.close();
    return baos.toByteArray().length;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!