Java 9 中的 Compact Strings 是什麼?


自 Java 9 起,JVM 優化了字串,使用了名為Compact Strings 的新功能。字串不再採用 char[array,而是表示為 byte[] 陣列。我們可以使用 UTF-16Latin-1 生成每個字元一或兩個位元組。如果 JVM 檢測到字串只包含 ISO-8859-1/Latin-1 字元,那麼該字串將在內部每個字元使用一個位元組。

建立字串時即可檢測到字串可否表示為 Compact 字串。該功能預設已啟用,可以使用 -XX:-CompactStrings 關閉。它不會還原為 char[] 實現,並會將所有字串儲存為 UTF-16.

// In Java 8
public class String {
   private final char[] value; // Stores characters in the string
      ---------
}

// In Java 9
public class String {
   private final byte[] value; // Stores characters in the string
   private final byte coder; // a flag whether to use 1 byte per character or 2 bytes per characters for this string

      ---------
}

更新日期:19-Mar-2020

285 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.