Memory usage of Java objects: general guide

On this page, we take a general look at how to calculate the memory usage of a Java object, or at least an estimate of its usage. (Note that using the Classmexer agent from this site— or VM insturmentation generally— you can query the size of a Java object from within your program.)

We'll generally be talking about the memory taken up on the heap by a given object under "normal circumstances". A couple of minor complications that we'll gloss over are that:

On this page, we look at the memory usage of a Java object generally. On the next pages, we'll look specifically at the memory usage of Strings and related objects.

General formula for calculating memory usage

In general, the heap memory used by a Java object in Hotspot consists of:

Sizes of primitive types

In case you're not familiar with the byte size of the different Java primitive data types, here is the complete list:

Java typeBytes required

You may have expected a boolean to take up a single bit, or an eighth of a byte, especially if an object had 8 boolean fields. In practice, Hotspot (and, I believe, VMs generally) allocate a whole byte to each boolean*.

* The reason is simply ease and efficiency of implementation: generally, we want to assign a "byte offset" to each field of a class and use a simple instruction to read/write an individual byte. It would be awkward if we had to cope with sub-byte offsets for certain fields, and it would require extra logic to read/write individual bits at a given position rather than just the whole byte each time the boolean was accessed.

Object overhead for "housekeeping" information

Instances of an object on the Java heap don't just take up memory for their actual fields. Inevitably, they also require some "housekeeping" information, such as recording an object's class, ID and status flags such as whether the object is currently reachable, currently synchronization-locked etc.

In Hotspot:

Other JVMs probably have a similar object overhead.

Object size granularity

In Hotspot, every object occupies a number of bytes that is a multiple of 8. If the number of bytes required by an object for its header and fields is not a multiple 8, then you round up to the next multiple of 8.

This means, for example, that:

Memory used by Java arrays

On the next page, we look in more detail at Java array memory usage.