Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the memory size of an ArrayList in Java

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.

like image 833
magallanes Avatar asked Jan 19 '11 19:01

magallanes


People also ask

How much memory is in an ArrayList?

Figure 10 shows that when an ArrayList is created, the result is an ArrayList object using 32 bytes of memory, along with an Object array at a default size of 10, totaling 88 bytes of memory for an empty ArrayList This means that the ArrayList is not accurately sized and therefore has a default capacity, which happens ...

What is ArrayList size in Java?

The size() method of java. util. ArrayList class is used to get the number of elements in this list. Syntax: public int size()

What is the size limit of ArrayList in Java?

ArrayList in Java has a get(int index) method. int is a signed 32 bit value, with a maximum value of 2,147,483,647. That is the largest possible value that can be accessed in an ArrayList .

How is ArrayList stored in memory Java?

ArrayLists use contiguous memory. All elements in the ArrayList are located next to each other in the same memory space. This is why retrieving an element from an ArrayList is so fast: given the location of the start of the ArrayList, you can know exactly where any element is located in memory.


4 Answers

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.

like image 145
bestsss Avatar answered Sep 22 '22 09:09

bestsss


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.

like image 22
Daniel DiPaolo Avatar answered Sep 25 '22 09:09

Daniel DiPaolo


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.

like image 29
Peter Lawrey Avatar answered Sep 23 '22 09:09

Peter Lawrey


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.

like image 30
rfeak Avatar answered Sep 22 '22 09:09

rfeak