How much memory a JAVA object consumes

Source: Internet
Author: User

How much memory a JAVA object consumes
First, let me pretend to say: when you write code to a certain level, you write a code, you probably know in your mind that the CPU usage for executing this code is 0.0000 ms, and the memory consumption is about several bytes. A person who does not think is stupid, but does not think. If you do not want to learn, you will be confused. If you do not want to learn, you will be confused. I recommend you read this book "deep understanding of Java Virtual Machine! Well, the installation is complete!

Object Memory size measurement

When optimizing the memory, you need to know the memory size occupied by each object,

Information to be stored in the memory of an instantiated object includes:

  1. Object Header (GC information, hash value, class definition reference, etc)
  2. Object member variables: including basic data types and references. If the member variable is a reference and other objects are referenced, the referenced object memory is calculated separately.

    For example, the following simple class definition:

    
      
    class MyClass { int a; Object object; }

    Instantiate an object:

    
      
    MyClass myClass = new MyClass();

    Object size:

    1. Own size (Shadow heap size)
    2. The size of the referenced object (Retained heap size ).

      myClassAfter the instance is created, the memory size ismyClassIts own size (Shadow heap size ). It includes the header size of the class, the size of an int, and the size of a reference.

      myClassMediumobjectA member variable is an object reference, and the referenced object also occupies a certain size.myClassThe size of the referenced object maintained by the instance, which is calledmyClassThe Retained heap size of the instance.

      This article discusses the size of the object itself, that is, the Shadow heap size. Retained heap size can be obtained by recursive calculation.

      Measurement tools

      Calculation of object size is availablejava.lang.instrument.InstrumentationOr dump the memory and use memory analyzer for analysis. This is an example of the Code java-object-size.

      Basic data type size

      The basic data type is as follows: From WIKI

      Type Size (bits) Bytes
      Boolean 8 1
      Byte 8 1
      Char 16 2
      Short 16 2
      Int 32 4
      Long 64 8
      Float 32 4
      Double 64 8
      Reference size

      On a 32-bit JVM, an object reference occupies 4 bytes. On a 64-bit JVM, it occupies 8 bytes. Passjava -d64 -versionDetermine whether the JVM is a 64-bit JVM.

      8 bytes are used to manage memory larger than 4 GB. If your program does not need to access memory larger than 4 GB,

      Available-XX:+UseCompressedOopsOption to enable pointer compression. SlaveJava 1.6.0_23This option is enabled by default. Availablejinfo -flag UseCompressedOops View.

      localhost:~ srain$ jinfo -flag UseCompressedOops 13133-XX:+UseCompressedOops
      Object Header size

      Object Header, with the following structure (source ):

      +------------------+------------------+------------------ +---------------.|    mark word     |   klass pointer  |  array size (opt) |    padding    |+------------------+------------------+-------------------+---------------'

      Each object has a mark work header and a reference pointing to class information. On a 32-bit JVM, mark word contains 4 bytes, and the entire header contains 8 bytes.

      If not enabledUseCompressedOopsThe object header size is 16 bytes on the 64-bit JVM.

      EnableUseCompressedOopsOn the 64-bit machine, the reference is 4 bytes, a total of 12 bytes. Alignment is 8 bits, which actually occupies 16 bytes.

      Object Memory Layout
      1. The memory usage of each object is aligned by 8 bytes.

      2. Empty object and class instance member variable

        An empty object is a non-inner-class without instance attributes.ObjectClass or direct inheritanceObjectNo class is added to the instance.

        An empty object does not contain any member variables. Its size is the size of the object header:

        • It occupies 8 bytes on a 32-bit JVM;
        • EnableUseCompressedOopsOn the 64-bit JVM, 12 + 4 = 16;
        • If not enabledUseCompressedOopsOn the 64-bit JVM, 16 + 4 = 20; after alignment, 24.
        • Object instance Member re-sorting

          Instance member variables follow the object header. Every member variable tries its best to keep its size aligned in the memory.

          For example, int Is aligned by 4 bits and long is aligned by 8 bits. In order to make the memory compact, the order of instance members in the memory may be different from that in the declaration order. The actual order is as follows:

          1. Doubles and longs
          2. Ints and floats
          3. Shorts and chars
          4. Booleans and bytes
          5. References

            This can save as much space as possible.

            For example:

            
                      
            class MyClass { byte a; int c; boolean d; long e; Object f; }

            Before rescheduling:

            
                      
            32 bit 64bit +UseCompressedOops [HEADER: 12 bytes] 8 [HEADER: 12 bytes] 12 [a: 1 byte ] 9 [a: 1 byte ] 13 [padding: 3 bytes] 12 [padding: 3 bytes] 16 [c: 4 bytes] 16 [c: 4 bytes] 20 [d: 1 byte ] 17 [d: 1 byte ] 21 [padding: 7 bytes] 24 [padding: 3 bytes] 24 [e: 8 bytes] 32 [e: 8 bytes] 32 [f: 4 bytes] 36 [f: 4 bytes] 36 [padding: 4 bytes] 40 [padding: 4 bytes] 40

            After sorting:

            
                      
            32 bit 64bit +UseCompressedOops [HEADER: 8 bytes] 8 [HEADER: 12 bytes] 12 [e: 8 bytes] 16 [e: 8 bytes] 20 [c: 4 bytes] 20 [c: 4 bytes] 24 [a: 1 byte ] 21 [a: 1 byte ] 25 [d: 1 byte ] 22 [d: 1 byte ] 26 [padding: 2 bytes] 24 [padding: 2 bytes] 28 [f: 4 bytes] 28 [f: 4 bytes] 32 [padding: 4 bytes] 32
          6. Instance members of the parent class and subclass

            The member variables of the parent class and subclass are stored separately. They are the instance members of the parent class. After the parent class instance member variable ends, it is aligned by four bits and then Child class instance member variables.

            
                      
            class A { byte a; } class B extends A { byte b; }

            The memory structure is as follows:

            
                      
            32 bit 64bit +UseCompressedOops [HEADER: 8 bytes] 8 [HEADER: 12 bytes] 12 [a: 1 byte ] 9 [a: 1 byte ] 13 [padding: 3 bytes] 12 [padding: 3 bytes] 16 [b: 1 byte ] 13 [b: 1 byte ] 17 [padding: 3 bytes] 16 [padding: 7 bytes] 24

            If the first member variable of the subclass is an 8-byte data type such as long or double, the parent class ends with no 8-bit alignment. Instance members smaller than 8 bytes of the subclass are first arranged until they can be 8 bytes aligned.

            
                      
            class A { byte a; } class B extends A{ long b; short c; byte d; }

            The memory structure is as follows:

            
                      
            32 bit 64bit +UseCompressedOops [HEADER: 8 bytes] 8 [HEADER: 8 bytes] 12 [a: 1 byte ] 9 [a: 1 byte ] 13 [padding: 3 bytes] 12 [padding: 3 bytes] 16 [c: 2 bytes] 14 [b: 8 bytes] 24 [d: 1 byte ] 15 [c: 4 byte ] 28 [padding: 1 byte ] 16 [d: 1 byte ] 29 [b: 8 bytes] 24 [padding: 3 bytes] 32

            In the above example, on a 32-bit JVM, B's two instance members c and d are advanced.

          7. A non-static internal class has a hidden external class reference.

            Memory usage of the array

            The array is also an object, so there is a header of the object. In addition, the array also has an int type that records the length of the array, followed by the elements of each array: basic data type or reference. 8-byte alignment.

            • On a 32-bit Machine

              Byte [0] 8-byte object header, 4-byte int length, 12 bytes, 16 bytes after alignment, actual byte [0] ~ Byte [4] is 16 bytes.

            • 64-bit + UseCompressedOops

              Byte [0] is 16 bytes in size, byte [1] ~ Byte [8] 24-byte size.

            • 64-bit-UseCompressedOops

              Byte [0], 16-byte header, 4-byte int length information, 20 bytes, after alignment 24 bytes. Byte [0] ~ Byte [4] is 24 bytes.

              String size
              Field Type 64 bit-UseCompressedOops 64 bit + UseCompressedOops 32 bit
              HEADER   16 12 8
              Value Char [] 8 4 4
              Offset Int 4 4 4
              Count Int 4 4 4
              Hash Int 4 4 4
              PADDING   4 4 0
              TOTAL   40 32 24

              Without calculating the Retained heap size referenced by value, the string itself needs to be 24 ~ 40 bytes.

               

              I found a blog posted on the Internet and spoke about it very well: http://yueyemaitian.iteye.com/blog/2033046:

               

              Import java. lang. instrument. instrumentation; import java. lang. reflect. array; import java. lang. reflect. field; import java. lang. reflect. modifier; import java. util. arrayDeque; import java. util. deque; import java. util. hashSet; import java. util. set;/*** tool class for byte usage of objects ** @ author tianmai. fh * @ date */public class SizeOfObject {static Instrumentation inst; public static void premain (String args, Instrumentation instP) {inst = instP ;} /*** calculate the space occupied by the current object directly, including the basic instance field size of the current class and super class, * Reference size of the Instance field of the reference type, total occupied space of the Instance basic type array, and occupied space of the Instance reference type array reference itself; * However, this does not include the size of the objects inherited by the superclass and the instance reference fields of the current class declaration, and the size of the objects referenced by the instance reference array. ** @ param obj ** @ return * /public static long sizeOf (Object obj) {return inst. getObjectSize (obj);}/*** recursively calculates the total space occupied by the current object, including the instance field size of the current class and super class and the size of the Instance field reference Object ** @ param objP * @ return * @ throws IllegalAccessException */public static long fullSizeOf (Object objP) throws IllegalAccessException {SetVisited = new HashSet(); DequeToBeQueue = new ArrayDeque(); ToBeQueue. add (objP); long size = 0L; while (toBeQueue. size ()> 0) {Object obj = toBeQueue. poll (); // when sizeOf is specified, it indicates the basic type and reference length, including the array size + = skipObject (visited, obj )? 0L: sizeOf (obj); Class
                               TmpObjClass = obj. getClass (); if (tmpObjClass. isArray () {// [I, [F basic type name length is 2 if (tmpObjClass. getName (). length ()> 2) {for (int I = 0, len = Array. getLength (obj); I <len; I ++) {Object tmp = Array. get (obj, I); if (tmp! = Null) {// The object toBeQueue. add (Array. get (obj, I) needs to be traversed in depth for non-basic types; }}} else {while (tmpObjClass! = Null) {Field [] fields = tmpObjClass. getDeclaredFields (); for (Field field: fields) {if (Modifier. isStatic (field. getModifiers () // static | field. getType (). isPrimitive () {// the basic type is continuous;} field. setAccessible (true); Object fieldValue = field. get (obj); if (fieldValue = null) {continue;} toBeQueue. add (fieldValue);} tmpObjClass = tmpObjClass. getSuperclass () ;}}return size;}/*** String. intern objects are excluded; computing objects are excluded, and endless loops are also avoided ** @ param visited * @ param obj * @ return */static boolean skipObject (SetVisited, Object obj) {if (obj instanceof String & obj = (String) obj ). intern () {return true;} return visited. contains (obj );}}


               

               

               

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.