Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Created December 25, 2014 13:19
Show Gist options
  • Save EmmanuelOga/404e8d52798473149aaf to your computer and use it in GitHub Desktop.
Save EmmanuelOga/404e8d52798473149aaf to your computer and use it in GitHub Desktop.
Determining java Obj size with java.lang.instrument package. Compile and put this class in a JAR:
// http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object
import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
/*
Add the following to your MANIFEST.MF:
Premain-Class: ObjectSizeFetcher
Use getObjectSize:
*/
public class C {
private int x;
private int y;
public static void main(String [] args) {
System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
}
}
/*
Invoke with:
java -javaagent:ObjectSizeFetcherAgent.jar C
NOTE: also check http://www.eclipse.org/mat/
http://www.javaworld.com/article/2077408/core-java/sizeof-for-java.html
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment