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.
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.
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.
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, calltrimToSize()
Technically speaking the
ArrayList
has anObject[]
where it stores the data.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.
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.
You can use something like
Runtime.getRuntime().totalMemory()
and its counterpartRuntime.getRuntime().freeMemory()
to get an educated guess, but that doesn't account for objects that are GC'ed between calls.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.