您的位置:首页 > 其它

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

2021-02-27 13:16 64 查看

目录
首先我们得先了解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;

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: