Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory usage for a specific list of object

i have a list of simples pojos (a User class) with about 15 simple fields & 1 arrayList. Those represent users & maybe 100 or 1000 of them will be store in memory in order to avoid to retrieve them from external system every time. (i'm using Ehcache)

I would like to know with a junit test how much memory is used by a list of K of those users. I have the intuition that simple pojo like those one even for a 1000 ones are not threatening in any way (in other words less than 100 Ko)

Thanks in advance for your anwser. i really appreciate your help.

like image 724
Omar Elfada Avatar asked Jan 26 '11 08:01

Omar Elfada


People also ask

How much memory does a list take up?

A list object has 64 bytes of overhead.

How do you know what memory an object needs?

getsizeof() function can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself.

How much memory does an object occupy?

Memory usage of some typical Java objects Theoretically, a long requires 4 more bytes compared to an int. But because object sizes will typically be aligned to 8 bytes, a boxed Long will generally take up 24 bytes compared to 16 bytes for an Integer.

How much memory is allocated to an object in Java?

Minimum object size is 16 bytes for modern 64-bit JDK since the object has 12-byte header, padded to a multiple of 8 bytes. In 32-bit JDK, the overhead is 8 bytes, padded to a multiple of 4 bytes.


1 Answers

You can calculate the memory used by the JRE before and after you create your object, in order to approximate how many bytes are being used by your object.

System.gc();
System.runFinalization();
Thread.sleep(1000);
long before = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

//build object here

System.gc();
System.runFinalization();
Thread.sleep(1000);
long after = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

long objectSize = after - before;
like image 127
dogbane Avatar answered Oct 13 '22 13:10

dogbane