10

I am studying java, and I remember reading somewhere that java objects, had some overhead inside the JVM, which was used for administration reasons by the virtual machine. So my question is, can someone tell me if and how I can get an object's total size in the HotSpot JVM, along with any overhead it may come with?

NlightNFotis
  • 9,559
  • 5
  • 43
  • 66
  • possible duplicate of [What is the memory consumption of an object in Java?](http://stackoverflow.com/questions/258120/what-is-the-memory-consumption-of-an-object-in-java) – Michael Borgwardt Jun 13 '12 at 09:51
  • Did you take a look at http://stackoverflow.com/questions/258120/what-is-the-memory-consumption-of-an-object-in-java ? – Ahamed Mustafa M Jun 13 '12 at 09:52
  • I am not exactly asking the same thing. I am asking about the overhead, and the total size so I can derive a percentage of the overhead against the total size. – NlightNFotis Jun 13 '12 at 09:53

2 Answers2

13

You can't get the overhead directly. The amount of overhead is implementation dependent, and can vary based on a number of factors (e.g. the precise JVM version, and whether you are on a 32 or 64bit JVM).

However it is reasonably safe to assume that in typical modern JVM implementations like HotSpot, the overhead per object is between 8 and 16 bytes. Arrays typically have an overhead that is 4 bytes larger than other objects (to contain the integer array length).

See also:

Community
  • 1
  • 1
mikera
  • 105,238
  • 25
  • 256
  • 415
0

Here is a snippet for object header, object overhead, array header, object reference. Hope it helps someone, if not the OP as it is a quite old question.

    private static int OBJ_HEADER;
    private static int ARR_HEADER;
    private static int INT_FIELDS = 12;
    private static int OBJ_REF;
    private static int OBJ_OVERHEAD;
    private static boolean IS_64_BIT_JVM;

     static {
    String arch = System.getProperty("sun.arch.data.model");

    IS_64_BIT_JVM = (arch == null) || arch.contains("32");
    OBJ_HEADER = IS_64_BIT_JVM ? 16 : 8;
    ARR_HEADER = IS_64_BIT_JVM ? 24 : 12;
    OBJ_REF = IS_64_BIT_JVM ? 8 : 4;
    OBJ_OVERHEAD = OBJ_HEADER + INT_FIELDS + OBJ_REF + ARR_HEADER;
       }

I should say that I know only the solution, but I haven't yet figured out why this works. This is why people should leave comments in their code... Oh, well, when I do figure it out, I will share the logic behind it.