Skip to content

Instantly share code, notes, and snippets.

@bnyeggen
Last active December 10, 2015 13:08
Show Gist options
  • Save bnyeggen/4438946 to your computer and use it in GitHub Desktop.
Save bnyeggen/4438946 to your computer and use it in GitHub Desktop.
Unsafe-based sizeof
// A simpler method than reflection-based traversal, using Unsafe
public static Unsafe getUnsafe() {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe) f.get(null);
}
public static long sizeOf(Object o) {
Unsafe u = getUnsafe();
HashSet<Field> fields = new HashSet<Field>();
Class c = o.getClass();
while (c != Object.class) {
for (Field f : c.getDeclaredFields()) {
if ((f.getModifiers() & Modifier.STATIC) == 0) {
fields.add(f);
}
}
c = c.getSuperclass();
}
// get offset
long maxSize = 0;
for (Field f : fields) {
long offset = u.objectFieldOffset(f);
if (offset > maxSize) {
maxSize = offset;
}
}
return ((maxSize/8) + 1) * 8; // padding
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment