关于String对象到底占多少字节?


首先我们得先了解java的对象结构

可以看到分别由三个部分组成对象头,实例数据,以及填充位

查看JDK1.8 String源码可以看到一个String对象由以下组成:

 @Stable
    private final byte[] value;


    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;

那么我们就可以根据这个来计算了,首先如果是一个空字符串那么就是:

空字符串

对象头(8字节)+实例数据(这里的实列数据有三个char数组,int,long那么就是16+4+8。由于在java中数组属于对象那么char数组也是对象头8+char数组的实例数据这里只算引用位4+填充4=16)+对齐填充(4)=40

有长度的String

显然有长度的String,多的数据都放在char数组里由于一个char是2字节那么看字符串长度可以计算出该String对象占用的空间为40+2*N。

由于后面JDK中在String中还引入了一个coder如下:

  /**
    * The identifier of the encoding used to encode the bytes in
    * {@code value}. The supported values in this implementation are
    *
    * LATIN1
    * UTF16
    *
    * @implNote This field is trusted by the VM, and is a subject to
    * constant folding if String instance is constant. Overwriting this
    * field after construction will cause problems.
    */
   private final byte coder;

当然计算方法也是一样的。

posted @ 2021-02-27 13:16  西伯利亚爱学习的狼  阅读(2371)  评论(0编辑  收藏  举报