Published 19 Sep, 2022

Java - JVM getObjectSize example

Category Java
Modified : Oct 03, 2022
84

I have some trouble on getting the size of an object in JVM. JDK 5 offer an interface Instrumentation to calculate through premain() function, but I do not know how to use it.

Can anybody help me?

Answers

There are 4 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Jvm. These have been categorized in sections for a clear and precise explanation.

29

the simplest and the most efficient solution is to use very small sizeof library

<dependency>
    <groupId>com.carrotsearch</groupId>
    <artifactId>java-sizeof</artifactId>
    <version>0.0.3</version>
</dependency>

you need to use this http://grepcode.com/file/repo1.maven.org/maven2/com.carrotsearch/java-sizeof/0.0.2/com/carrotsearch/sizeof/RamUsageEstimator.java?av=f

shallowSizeOf() method or sizeOf()

That's really the simplest working fast solution i found on this topic so far...


40

Another open source project that may help you is Jamm which uses a JVM agent as well.


29

You might find it helpful to use the MemoryMeasurer library, which packages simple memory measurement into a relatively straightforward API. (Alternatively, you can look at its source code to see how it uses instrumentation.)


25

Here we have a very good article by Dustin Marx that I can refer you .

http://java.dzone.com/articles/estimating-java-object-sizes