What is the memory size of an ArrayList in Java

2019-02-22 12:15发布

I have an ArrayList<Obj> and I wish to know how much memory it is using.

The Obj is variant so, it is not as easy as multiply the number of elements in the array per the size of an object.

8条回答
▲ chillily
2楼-- · 2019-02-22 12:30

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.

查看更多
小情绪 Triste *
3楼-- · 2019-02-22 12:31

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.

查看更多
爷的心禁止访问
4楼-- · 2019-02-22 12:31

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.

查看更多
Ridiculous、
5楼-- · 2019-02-22 12:33

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.

查看更多
叼着烟拽天下
6楼-- · 2019-02-22 12:36

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.

查看更多
Viruses.
7楼-- · 2019-02-22 12:42

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.

查看更多
登录 后发表回答