File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes calculating memory usage Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "calculating memory usage" Watch "calculating memory usage" New topic

calculating memory usage

mark I thomas
Ranch Hand

Joined: Apr 07, 2008
Posts: 86
If I have

1)a collection of 100 objects, each object has 10 attributes defined in POJO class and each attribute is set to have an Integer type with dummy value of 30.
2) a collection of 100 objects, each object has 1 attribute defined in POJO class and this attribute has an Integer value of 30.

Can I say the first collection approximately occupies 10 times memory than the second collection ? Can I simply calculate it this way ?

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15082

That is a reasonable way of estimating the memory use of objects, yes.

Suppose that the overhead for one of your POJO objects is P bytes, and the size of an Integer object is Q bytes. Then the total size of one of your POJOs will be P + Q bytes. If you now have 10 Integer objects instead of one Integer object in your POJO, the size will become P + 10 * Q bytes.

So 100 POJOs in the first case will be 100 * (P + Q) bytes, and 100 POJOs in the second case will be 100 * (P + 10 * Q) bytes.

If P is small compared to Q, then in the second case it will take approximately 10 times as much memory.

It's not easy to find out the exact size of objects in Java, or what the overhead per object (P) is, because it depends on the Java implementation (it might be different with different versions of Java, on different operating systems, or when using Java implementations from different vendors).

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

It might also be the case that you have thousands of different Integer(30) objects, or just one of them which everything refers to (in this simple example). This could make a difference, but what you said in your original post was approximately correct. For some value of "approximately".
I agree. Here's the link:
subject: calculating memory usage
jQuery in Action, 3rd edition