目錄
首先我們得先了解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;
當然計算方法也是一樣的。