关于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;

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值