Home  >  Article  >  Java  >  A brief analysis of Java object size

A brief analysis of Java object size

黄舟
黄舟Original
2017-03-15 11:35:571616browse


I had a whim recently and suddenly became interested in the memory size of Java objects. I went to collect some information on the Internet and sorted it out. I hope you can help me.
If: you can calculate the memory size occupied by the object new String ("abc") in the JVM (compressed size 48B, uncompressed size 64B in 64-bit JDK7), then you can end it here~


Memory layout of Java objects: Object header (Header), instance data (Instance Data) and alignment padding (Padding) ## #. The object header of the virtual machine includes two parts of information. The first part is used to
store the runtime data of the object itself , such as hashCode, GC generation age, lock status flag, lock held by the thread, and bias Thread ID, bias timestamp, etc. The length of this part of data is 4B and 8B respectively in 32-bit and 64-bit virtual machines (pointer compression is not turned on). It is officially called "Mark Word". The other part of the object is the
type pointer (klass) , which is the pointer of the object to its class metadata. The virtual machine uses this pointer to determine which class the object is an instance of. In addition, if the object is a Java array, there must be a piece of data in the object header to record the length of the array, because the virtual machine can determine the size of the Java object through the metadata information of ordinary Java objects, but from the metadata of the array But cannot determine the size of the array.
The object header occupies 8B on 32-bit systems and 16B on 64-bit systems. Whether it is a 32-bit system or a 64-bit system, objects are 8-byte aligned. When Java turns on pointer compression in 64-bit mode, the header will be 4B larger than in 32-bit mode (the mark area is shifted by 8B, and the kclass area is compressed). If pointer compression is not turned on, the header will be 8B larger (both mark and kclass are compressed). is 8B) , in other words, HotSpot's alignment is 8-byte alignment: (object header + instance data + padding)%8 is equal to 0 and 0<=padding<8. The following instructions are based on HotSpot.


As mentioned in Reference 2, the java.lang.instrument.Instrumentation provided after JDK5 provides a rich API for tracking various aspects of structure and measuring object size. However, this thing requires the use of java agent. As for the agent and Instrumentation, I will not explain them here. I will only explain how to use them.

This class is provided in Reference Material 3. I personally think it is very practical. The code is shown in Appendix 1 below (the code is relatively long, so I will simply put it at the end of the article):
This code can be copied directly, and then Pack it into a jar package (named agent.jar. If the packaging is not successful, you can directly download the package packaged by the blogger). Pay attention to adding a line in META-INF/MANIFEST.MF:

Premain-Class: com.zzh.size.MySizeOf (注意":"后面的空格,否则会报错:invalid header field.)

Give an example Case, the code is as follows (the blogger’s system is 64-bit and uses 64-bit JDK7):

import com.zzh.size.MySizeOf;public class ObjectSize
{    public static void  main(String args[])
    {
        System.out.println(MySizeOf.sizeOf(new Object()));
    }
}

Next, compile and run, the steps are as follows:

  1. Compile (agent.jar is placed in the current directory): javac -classpath agent.jar ObjectSize.java

  2. Run: java -javaagent:agent.jar ObjectSize (output result: 16, As for the analysis of this result, we will elaborate on it later)

JDK6 introduces the parameter -XX:+UseCompressedOops. This parameter will be automatically turned on by default in 32G memory. Pointer compression can be turned off by adding -XX:-UseCompressedOops to the run parameters.

Using Instrumentation to test the size of an object is just to express the size of an object more vividly. In fact, when an object is created, its size can be calculated manually. Code case practice is used to prove the rationality and correctness of theoretical knowledge. , the specific algorithm is reflected in the code case below.

Supplement: The memory usage of primitive type is as follows:

Primitive TypeMemory Required(bytes)boolean1byte1short2char2int4##floatlongdouble

 引用类型在32位系统上每个占用4B, 在64位系统上每个占用8B。


案例分析
 扯了这么多犊子,估计看的玄乎玄乎的,来几段代码案例来实践一下。

案例1:上面的new Object()的大小为16B,这里再重申一下,博主测试机是64位的JDK7,如无特殊说明,默认开启指针压缩。

new Object()的大小=对象头12B(8Bmak区,4Bkclass区)+padding的4B=16B

案例2

    static class A{        int a;
    }    static class B{        int a;        int b;
    }    public static void  main(String args[])
    {
        System.out.println(MySizeOf.sizeOf(new Integer(1)));
        System.out.println(MySizeOf.sizeOf(new A()));
        System.out.println(MySizeOf.sizeOf(new B()));
    }

输出结果:

(指针压缩) 16    16    24
(指针未压缩)24    24    24

分析1(指针压缩):

new Integer(1)的大小=12B对象头+4B的实例数据+0B的填充=16Bnew 
A()的大小=12B对象头+4B的实例数据+0B的填充=16B
new B()的大小=12B对象头+2*4B的实例数据=20B,填充之后=24B

分析2(指针未压缩):

new Integer(1)的大小=16B对象头+4B的实例数据+4B的填充=24B
new A()的大小=16B对象头+4B的实例数据+4B的填充=24B
new B()的大小=16B对象头+2*4B的实例数据+0B的填充=24B

案例3

System.out.println(MySizeOf.sizeOf(new int[2]));
System.out.println(MySizeOf.sizeOf(new int[3]));
System.out.println(MySizeOf.sizeOf(new char[2]));
System.out.println(MySizeOf.sizeOf(new char[3]));

输出结果:

(指针压缩) 24    32    24    24
(指针未压缩) 32    40    32    32

分析1(指针压缩):

new int[2]的大小=12B对象头+压缩情况下数组比普通对象多4B来存放长度+2*4B的int实例大小=24B
new int[3]的大小=12B对象头+4B长度+3*4B的int实例大小=28B,填充4B =32B
new char[2]的大小=12B对象头+4B长度+2*2B的实例大小=20B,填充4B=24B
new char[3]的大小=12B对象头+4B长度+3*2B的实例大小+2B填充=24B
(PS:new char[5]的大小=32B)

分析2(指针未压缩):

new int[2]的大小=16B对象头+未压缩情况下数组比普通对象多8B来存放长度+2*4B实例大小=32B
new int[3]的大小=16B+8B+3*4B+4B填充=40B
new char[2]的大小=16B+8B+2*2B+4B填充=32B
new char[2]的大小=16B+8B+3*2B+2B填充=32B
(PS:new char[5]的大小为40B)

案例4(sizeOf只计算本体对象大小,fullSizeOf计算本体对象大小和引用的大小,具体可以翻阅附录1的代码).

System.out.println(MySizeOf.sizeOf(new String("a")));
System.out.println(MySizeOf.fullSizeOf(new String("a")));
System.out.println(MySizeOf.fullSizeOf(new String("aaaaa")));

输出结果:

(指针压缩)24    48    56    
(指针未压缩)32    64   72

分析1(指针压缩):

翻看String(JDK7)的源码可以知道,
String有这几个成员变量:(static变量属于类,不属于实例,所以声明为static的不计入对象的大小)
private final char value[];
private int hash;
private transient int hash32 = 0;

MySizeOf.sizeOf(new String("a"))的大小=12B对象头+2*4B(成员变量hash和hash32)+4B(压缩的value指针)=24B
MySizeOf.fullSizeOf(new 
String("a"))的大小=12B对象头+2*4B(成员变量hash和hash32)+4B指针+
(value数组的大小=12B对象头+4B数组长度+1*2B实例大小+6B填充=24B)=12B+8B+4B+24B=48B
(PS: new String("aa"),new String("aaa"),new String("aaaa")的fullSizeOf大小都为48B)
MySizeOf.fullSizeOf(new String("aaaaa"))的大小=12B+2*4B+4B+(12B+4B+5*2B+6B填充)=24B+32B=56B

分析2(指针未压缩)

MySizeOf.sizeOf(new String("a"))的大小=16B+2*4B+8B(位压缩的指针大小) =32B
MySizeOf.fullSizeOf(new String("a"))的大小=16B对象头+2*4B(成员变量hash和hash32)+8B指针+(value数组的大小=16B对象头+8B数组长度+1*2B实例大小+6B填充=32B)=32B+32B=64B
(PS: new String("aa"),new String("aaa"),new String("aaaa")的fullSizeOf大小都为64B)
MySizeOf.fullSizeOf(new String("aaaaa"))的大小=16B+2*4B+8B+(16B+8B+5*2B+6B填充)=32B+40B=72B

 这些计算结果只会少不会多,因为在代码运行过程中,一些对象的头部会伸展,mark区域会引用一些外部的空间(轻量级锁,偏向锁,这里不展开),所以官方给出的说明也是,最少会占用多少字节,绝对不会说只占用多少字节。

如果是32位的JDK,可以算一下或者运行一下上面各个案例的结果。

 看来上面的这些我们来手动计算下new String()的大小:
1. 指针压缩的情况

12B对象头+2*4B实例变量+4B指针+(12B对象头+4B数组长度大小+0B实例大小)=24B+16B=40B
  1. 指针未压缩的情况

16B+2*4B+8B指针+(16B+8B数组长度大小+0B)=32B+24B=56B

 所以一个空的String对象最少也要占用40B的大小,所以大家在以后应该编码过程中要稍微注意下。其实也并不要太在意,相信能从文章开头看到这里的同学敲的代码也数以万计了,不在意这些也并没有什么不妥之处,只不过如果如果你了解了的话对于提升自己的逼格以及代码优化水平有很大的帮助,比如:能用基本类型的最好别用其包装类。

附:agent.jar包源码

package com.zzh.size;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;
public class MySizeOf{
     static Instrumentation inst;  

        public static void premain(String args, Instrumentation instP) {  
            inst = instP;  
        }  

        /** 
         * 直接计算当前对象占用空间大小,包括当前类及超类的基本类型实例字段大小、<br></br> 
         * 引用类型实例字段引用大小、实例基本类型数组总占用空间、实例引用类型数组引用本身占用空间大小;<br></br> 
         * 但是不包括超类继承下来的和当前类声明的实例引用字段的对象本身的大小、实例引用数组引用的对象本身的大小 <br></br> 
         * 
         * @param obj 
         * @return 
         */  
        public static long sizeOf(Object obj) {  
            return inst.getObjectSize(obj);  
        }  

        /** 
         * 递归计算当前对象占用空间总大小,包括当前类和超类的实例字段大小以及实例字段引用对象大小 
         * 
         * @param objP 
         * @return 
         * @throws IllegalAccessException 
         */  
        public static long fullSizeOf(Object objP) throws IllegalAccessException {  
            Set<Object> visited = new HashSet<Object>();  
            Deque<Object> toBeQueue = new ArrayDeque<>();  
            toBeQueue.add(objP);  
            long size = 0L;  
            while (toBeQueue.size() > 0) {  
                Object obj = toBeQueue.poll();  
                //sizeOf的时候已经计基本类型和引用的长度,包括数组  
                size += skipObject(visited, obj) ? 0L : sizeOf(obj);  
                Class<?> tmpObjClass = obj.getClass();  
                if (tmpObjClass.isArray()) {  
                    //[I , [F 基本类型名字长度是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) {  
                                //非基本类型需要深度遍历其对象  
                                toBeQueue.add(Array.get(obj, i));  
                            }  
                        }  
                    }  
                } else {  
                    while (tmpObjClass != null) {  
                        Field[] fields = tmpObjClass.getDeclaredFields();  
                        for (Field field : fields) {  
      
       if (Modifier.isStatic(field.getModifiers())   //静态不计  
                                    || field.getType().isPrimitive()) {    //基本类型不重复计  
                                continue;  
                            }  

                            field.setAccessible(true);  
                            Object fieldValue = field.get(obj);  
                            if (fieldValue == null) {  
                                continue;  
                            }  
                            toBeQueue.add(fieldValue);  
                        }  
                        tmpObjClass = tmpObjClass.getSuperclass();  
                    }  
                }  
            }  
            return size;  
        }  

        /** 
         * String.intern的对象不计;计算过的不计,也避免死循环 
         * 
         * @param visited 
         * @param obj 
         * @return 
         */  
        static boolean skipObject(Set<Object> visited, Object obj) {  
            if (obj instanceof String && obj == ((String) obj).intern()) {  
                return true;  
            }  
            return visited.contains(obj);  
        }  
}
4
8
8

The above is the detailed content of A brief analysis of Java object size. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn