前言
String 是我們使用最頻繁的物件,使用不當會對記憶體、程式的性能造成影響,本篇文章全面介紹一下 Java 的 String 是如何演進的,以及使用 String 的注意事項,
下面的輸出結果是什么?
@Test
public void testString() {
String str1 = "abc";
String str2 = new String("abc");
String str3 = str2.intern();
System.out.println(str1 == str2);
System.out.println(str2 == str3);
System.out.println(str1 == str3);
}
這段代碼涉及了 Java 字串的記憶體分配、新建物件和參考等方面的知識,輸出結果是:
false
false
true
String 物件的實作方式
String 物件的實作方式,在 Java 6、Java 7/8、Java 9 中都有很大的區別,下面是一張簡要的對比圖:

Java 6 的實作方式
String 對 char 陣列進行了封裝,主要有四個成員變數:
- char 陣列
- 偏移量 offset
- 字符數量 count
- 哈希值 hash
String 物件可以通過 offset 和 count 在 char[] 陣列中獲取對應的字串,這樣做可以高效、快速地共享陣列物件,節省記憶體空間,但是這種方法經常導致記憶體泄漏,
這是因為,假如有一個非常大的字串陣列物件 a,后來有一個小的字串參考僅參考其中很少的字符 b,那么會新建大的陣列 char[],當 a 被釋放后,char[] 的參考并不能被 GC,因為 b 還在參考,
Java 7/8 的實作方式
String 類去掉了 offset 和 count,String.substring 方法也不再共享char[],從而解決了記憶體泄漏問題,
Java 9 的實作方式
char[] → byte[],同時新增了coder屬性,標識字符編碼,這是因為 char 字符占 16 位(2個位元組),如果僅存盤單位元組編碼的字符就非常浪費空間,
coder 屬性的作用是標識字串是否為 Latin-1(單位元組編碼),0 標識是 Latin-1,1 代表是 UTF-16,
Java 11 中的 java.lang.String#substring(int, int) 方法如下:
public String substring(int beginIndex, int endIndex) {
int length = length();
checkBoundsBeginEnd(beginIndex, endIndex, length);
int subLen = endIndex - beginIndex;
if (beginIndex == 0 && endIndex == length) {
return this;
}
return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
: StringUTF16.newString(value, beginIndex, subLen);
}
String 在 JVM 中是如何存盤的?
這是一個很重要的問題,相信大部分人都不能描述清楚,因為 JVM 的實作改了很多版……
在 JDK 1.7 之前,運行時常量池邏輯包含字串常量池,都存在方法區中,方法區在 HotSpot 虛擬機的實作為永久代,
在 JDK 1.7 中,字串常量池 → 堆,運行時常量池仍然在方法區中,
在 JDK 1.8 中,HotSpot 移除了永久代,使用元空間(Metaspace)代替,這時候字串常量池在堆中,運行時常量池在元空間(Metaspace),
永久代 VS 元空間(Metaspace)
元空間的本質和永久代類似,都是對 JVM 規范中方法區的實作,不過元空間與永久代之間最大的區別在于:元空間并不在虛擬機中,而是使用本地記憶體,
一句話總結
在新版 JDK 實作(畢竟 Java 8 都已經是老古董,Java 15 都發布了)中,字串常量池是在堆中,
使用 String.intern 節省記憶體
雖然我還沒有在專案中實際應用過,不過這個函式應該還挺有用的,能夠復用 Java 中的字串常量,文章開頭的代碼中,System.out.println(str1 == str3); 回傳 true,就是因為 java.lang.String#intern 方法檢測到字串常量池有這個物件時,能夠直接復用字串常量池的物件,不會額外創建字串常量,
String str1 = "abc";
String str2 = new String("abc");
注意上面的代碼中,new String("abc") 里面的字串 abc 與 str1 的 abc 不同,是在字串常量池新創建的 abc,
String.intern 的代碼注釋如下,
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
* @jls 3.10.5 String Literals
*/
public native String intern();
公眾號
coding 筆記、點滴記錄,以后的文章也會同步到公眾號(Coding Insight)中,希望大家關注_
代碼和思維導圖在 GitHub 專案中,歡迎大家 star!

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/228373.html
標籤:Java
上一篇:MyBatis學習05
下一篇:Maven 依賴樹的決議規則
