How a Java object consumes memory

Source: Internet
Author: User

This article uses a 32-bit JVM, jdk1.6.    This article is basically translated, plus some of their own understanding, the original text see the article under the link. In this article, we discuss how to calculate or estimate how much memory space a Java object occupies. (Note that using the Classmexer agent or VM insturmentation can query how much memory is consumed by a Java object.) In general, we discuss the memory of an object in the heap, provided that it is under "normal state." We ignore the following two scenarios.
    • In some cases, the JVM does not necessarily place objects in the heap. For example, a simple thread-local object can be stored in the stack.
    • The memory occupied by an object also depends on its current state: for example, whether the synchronization lock for this object is in a competitive state, or whether the object is being reclaimed by GC.
general method for calculating memory consumptionIn general, in a hotspot, the memory consumption of a Java object consists of the following four aspects:

    1. The object header, including the state of some objects. The memory consumption of an instance object in the heap is not only spent on its properties, but this object also requires some additional information, such as a class reference to hold an object and a status token that determines whether the object is reachable, the current synchronization lock, and so on.

      In the hotspot: (other JVM cases are similar to the following description.) )

      • An ordinary object requires 8 bytes of extra memory space
      • An array requires 12 bytes (8 bytes + 4 of the normal object header)
    2. Basic types of memory consumption, such as int,long,float , etc.
    3. The memory consumption of a reference property, which consumes 4 bytes per reference.
    4. Padding, an object may have a fraction of the consumption wasted on the padding above. In a hotspot, the smallest unit of memory allocated to an object is 8 bytes, so the number of bytes per object can be divisible by 8. If the number of bytes in an object is not a multiple of 8, then the nearest number that can be divisible by 8 is rounded up.

For example, an empty instance object occupies 8 bytes. A containing a BooleanThe object of the property occupies 16 bytes of memory: The object header occupies 8, BooleanThe attribute takes up 1, 8+1=9 bytes, because 9 is not a multiple of 8, up to the smallest number 16 divisible by 8. A total of 8 BooleanThe object of the property also occupies 16 bytes of memory: The object Header 8, BooleanThe attributes account for 1*8, altogether 16, 16 divisible by 8, and no padding bytes are required. One contains two long attributes, 3 intProperties and a BooleanObject consumes 40 bytes of memory:
    • Object header takes up 8 bytes
    • 2 A long takes 16 bytes
    • 3 int occupies 12 bytes
    • 1 boolean takes up 1 bytes
    • The padding byte occupies 3 bytes. The front occupies a total of 37 bytes, 37 can not be divisible by 8, take 40 bytes.
How to calculate the memory used by a Java arrayBefore we write about how to calculate the memory consumption of a Java object, we discuss the following special case array. We know:
    • In Java, an array is a special type of object
    • A multidimensional array is an array of simple arrays
For example, each row of a two-dimensional array is a separate array object memory usage of a single arrayA one-dimensional array is an object, and an array has an object header, but this object takes up 12 bytes and an additional 4 bytes to store the length of the array. How many bytes are required for each element, depending on the type of element. Each element requires 4 bytes to store its reference. And if the total number of bytes is not 8 multiples, the same padding bytes are required. memory consumption of two-dimensional arraysIn the C language, a two-dimensional array (in fact any multidimensional array) is essentially a one-dimensional array that is implemented by pointer manipulation. But this is not the case in Java, where multidimensional arrays are in fact a series of inline arrays.    This means that each row of a two-dimensional array has the same memory overhead as the object, because he is essentially a separate object. For example, there is a 10x10 intArray, first, the "outer" array has a 12-byte object header overhead. Then there are 10 elements, each of which stores a reference to an array of 10 elements. The above overhead is 12+4*10=52 bytes. Then there is an array object in each row, the object header cost of an array object is 12 bytes, and there are 10 int. Overhead 10*4 = 40 bytes, plus 4 padding bytes, so the array object for each row occupies 56 bytes. So altogether there are 56*10+52 = 612 bytes, plus 4 padding bytes altogether 616 bytes. Therefore, the total number of bytes will be more than if only the 10*10*4=400 bytes are considered. Multi-dimensional arrays and two-dimensional arrays are similarly available. memory consumption of JAVA string and string -related objectsOur application basically uses strings, if you use C, and ASCII encoding, strings consist of numbers, letters, or some special symbols. Then the size of each string is the number of characters * 1 bytes. But Java is not like this: first, each object contains an object header, so an object consumes a minimum of 8 bytes.
    • A Java String contains more than one object
    • A Java char occupies two bytes.
    • A Java object contains some extra variables.
How to calculate the use of string memoryThe first one that takes up a minimum byte String, which can be calculated using the following formula.
8 * (int) (((No chars) * 2) +/8)
or, use this method to calculate:
    • The number of characters in a string * 2 bytes
    • Added 38
    • If the result is not a multiple of 8, the number that is larger than the result and closest can be divisible by 8.
The result is StringThe minimum number of bytes of memory consumed in the heap. Further in general, the above formula can be used for "new" String, however, there are other situations as follows:
    • If a string is a substring of another string , the string will be larger than the minimum value mentioned above.
    • A substring can share the same character array, so in general, a parent string with several sub-characters consumes less than the sum calculated with the formula above.
understand how a string consumes memoryTake a look at each StringObject, one of the various properties of the StringInclude the following attributes:
    • A char array (which is a separate object used to store characters in a string)
    • The offset property of an int , which indicates that the string starts with the first character in the char array.
    • The Count property of an int (the length of the string)
    • The hash attribute of the last int (used to store the value of Hashcode)
In other words, even a StringDoes not contain any characters, it also needs to consume 4 bytes on the reference of the array, plus 3 intThe properties of the type, 3*4=12 bytes, plus 8 bytes of the object header, are 24 bytes above (currently no padding bytes are required). Then, a CharThe object header of an array requires 12 bytes, plus 4 padding bytes, and an empty string consumes 40 bytes. If StringContains 17 characters, then StringThe object itself requires 24 bytes, but now the 17-character CharThe array requires 12 bytes plus 17*2=34 bytes, 12+17*2=46 bytes, 46 not multiples of 8, plus padding bytes 46+2=48 bytes, then 17 characters of the string will use 48+24 = 72 bytes, you can see the C language occupies 18 bytes StringOccupies 72 bytes in Java. memory consumption of substringsYou may wonder why the string will have an offset property and a Count property. Why CharDo the characters in the array directly correspond to the entire string? Is this, when you create a substring, the newly created substring of the CharThe array is actually a pointer to the parent string CharArray, which is a parent-child string that shares a CharArray. (But they have different offset and count). Whether this is a good thing or a bad thing depends on how you use:
    • If you need to use the parent string after creating the substring, you can save some memory.
    • If the parent string is no longer needed after the substring is created, then the memory is wasted

?

For example, the following code
String str = "Some longish string ..."; str.substring (5, 4);

in this code, the char array of STR consists of more than 4 characters, which includes the complete string "Some longish string ...", but Str's Offset,count attribute has changed. If this waste of memory is unacceptable in the application, then I can recreate a new String :
String str = "Some longish string ..."; str = new String (str.substring (5,4));
creating a new Stringin this way, the char array no longer points directly to "Some longish String ...", but instead creates a 4-character char array object that fits.

Information:

Http://www.javamex.com/tutorials/memory/object_memory_usage.shtml describes the memory footprint of Java objectsHttp://www.javamex.com/tutorials/memory/array_memory_usage.shtml introducing the memory footprint of the Java arrayHttp://www.javamex.com/tutorials/memory/string_memory_usage.shtml describes the memory footprint of Java strings

How a Java object consumes memory

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.