前言
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)中,希望大家關注_