Sometimes I need to know the exact size of a Java object, and that can be tricky to compute by hand. Here is a way within Eclipse and a Maven project.
Download, copy it to e.g. src/test/resources/memory/classmexer.jar
and add it to your project, e.g.
<dependency>
<groupId>classmexer</groupId>
<artifactId>classmexer</artifactId>
<version>0.3</version>
<scope>system</scope>
<systemPath>${basedir}/src/test/resources/memory/classmexer.jar</systemPath>
</dependency>
Instantiate the agent
- Run > Run Configurations...
- Select the class or test
- Tab "Arguments", box "VM arguments:", add
-javaagent:src/test/resources/memory/classmexer.jar
Measure the memory of java objects
import static com.javamex.classmexer.MemoryUtil.deepMemoryUsageOf;
Map<Integer, String> mymap = new HashMap<Integer, String>();
mymap.put(1, "hello");
System.out.println(deepMemoryUsageOf(mymap));
mymap.put(2, "a");
System.out.println(deepMemoryUsageOf(mymap));
mymap.put(3, "world");
System.out.println(deepMemoryUsageOf(mymap));
240
336
440
comments powered by Disqus