Explain Codes LogoExplain Codes Logo

Calculate size of Object in Java

java
object-measurement
memory-measurer
unsafe-class
Alex KataevbyAlex Kataev·Jan 30, 2025
TLDR

Use the Instrumentation API to rapidly estimate an object's size in Java. All you need is to set up a Java agent with a premain method, invoke Instrumentation.getObjectSize(Object), and launch your app with -javaagent:

public class ObjectSizeAgent { private static Instrumentation inst; // If 007 was a Java agent public static void premain(String args, Instrumentation inst) { ObjectSizeAgent.inst = inst; } // How heavy is my object? Let me check its weight public static long sizeOf(Object obj) { return inst.getObjectSize(obj); } }

Put it to work this way:

long size = ObjectSizeAgent.sizeOf(new MyClass()); System.out.println("Size: " + size); // "My MyClass weighs this much, not bad eh?"

If rough sizes are acceptable for your workflow, you could check out third-party libraries such as JAMM. However, keep in mind that Instrumentation delivers the most accurate outcomes as it is part of the Java platform.

Deep diving into object size calculation

Size calculation: unique with Memory-measurer

Size extrapolation: The Unsafe way

Trading off between size calculation methods

Deep diving into object size calculation

Size calculation: diving deep with Memory-measurer

For an object graph comprehensive analysis, consider the Memory-measurer library. Tools like ObjectGraphMeasurer can calculate the size of the entire object graph, not just the surface-level object. This can be key when comparing complex data structures:

long deepSize = ObjectGraphMeasurer.measure(new MyClass()); System.out.println("Deep Size: " + deepSize); // "Memory-measurer shows it's much heavier than you think!"

You can find the library's source code and usage examples readily available on its GitHub repo.

Size extrapolation: Going Unsafe

For those familiar with the internals of Java, the Unsafe class offers a powerful toolbox. It enables calculating object sizes taking into account heap alignment and field padding:

Unsafe theUnsafe = // get instance of Unsafe; handle with care! long objectSize = theUnsafe.getAddress( theUnsafe.toAddress(obj) + theUnsafe.objectFieldOffset( someField)); // "Whoa! I just measured you using Unsafe, feel special now?"

This approach calls for an in-depth understanding of the JVM memory model, NR_BITS, and how bytes and words size relate to each other.

Trading off between size calculation methods

While Instrumentation API is a commonplace, it demands to set up an agent. Contrarily, Memory-measurer could be attractive for rapid development and less complex scenarios because of its simplified usage.

Making the choice: deciding and managing potential issues

Trade-off analysis: deciding on pre-agent set up

Custom tailoring: choosing the size measurement method