Learn about object overhead in JVM

后端 未结 3 1446
离开以前
离开以前 2021-01-12 04:52

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. S

3条回答
  •  生来不讨喜
    2021-01-12 05:21

    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.

提交回复
热议问题