Java 有 JVM 與垃圾回收器代管記憶體,但使用不當仍會出問題,最常見的兩種是記憶體溢出與記憶體洩漏。
記憶體溢出(out of memory):通俗說就是記憶體不夠用,例如在無限迴圈中不斷建立大物件,很快就會爆。
記憶體洩漏(leak of memory):為物件配置了記憶體,物件已不再使用卻沒被釋放,一直佔著空間,可用記憶體越來越少,就像漏了一樣。
substring(int beginIndex, int endIndex) 回傳從 beginIndex 開始、到 endIndex - 1 結束的子字串,索引從 0 起算,包含 beginIndex 但不含 endIndex。
String x = "abcdef"; x = x.substring(1, 3); System.out.println(x); // 輸出 bc
String 是不可變類,第二句重新賦值時 x 會指向一個新物件。但 heap 中真正发生的事,取決於哪個 JDK 版本。
String 內部以 char 陣列儲存,JDK6 的 String 有三個欄位:char[] value、int offset、int count,分別是真正的字元陣列、起始位置與字元數。呼叫 substring 時會建立新字串,但 value 仍指向父字串那個陣列,父子唯一的差別只是 offset 與 count 不同。
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) throw new StringIndexOutOfBoundsException(beginIndex);
if (endIndex > count) throw new StringIndexOutOfBoundsException(endIndex);
if (beginIndex > endIndex) throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value); // 共用父陣列
}
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
String str = "abcdefghijklmnopqrst"; String sub = str.substring(1, 3); str = null;
sub 由 str 截取而來,兩者的內部 char 陣列是同一個(含 a 到 t 的大陣列),差別只在 offset 與 count。第三句把 str 設為 null,本意是釋放空間,但 GC 無法回收這個大陣列,因為 sub 內部還引用著它——即使 sub 只用其中一小段。當 str 原本是非常大的字串時,這種浪費會非常明顯,甚至造成效能問題。
舊的解法是用字串拼接強迫產生新陣列:
String str = "abcdefghijklmnopqrst"; String sub = str.substring(1, 3) + ""; str = null;
拼接會建立新字串並配置新的 char 陣列,父陣列不再被引用,下次 GC 時整塊空間就能回收。寫法不太好看,所以 JDK7 直接改了實作。
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) throw new StringIndexOutOfBoundsException(beginIndex);
if (endIndex > value.length) throw new StringIndexOutOfBoundsException(endIndex);
int subLen = endIndex - beginIndex;
if (subLen < 0) throw new StringIndexOutOfBoundsException(subLen);
return ((beginIndex == 0) && (endIndex == value.length)) ? this :
new String(value, beginIndex, subLen);
}
public String(char value[], int offset, int count) {
if (offset < 0) throw new StringIndexOutOfBoundsException(offset);
if (count < 0) throw new StringIndexOutOfBoundsException(count);
if (offset > value.length - count) throw new StringIndexOutOfBoundsException(offset + count);
this.value = Arrays.copyOfRange(value, offset, offset + count);
}
關鍵是最後那句 Arrays.copyOfRange,它會配置一個新陣列並把需要的字元複製進去:
public static char[] copyOfRange(char[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0) throw new IllegalArgumentException(from + " > " + to);
char[] copy = new char[newLength]; // 建立新陣列
System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength));
return copy;
}
這樣父子字串不再有交集,父字串的引用失效後 GC 就能及時回收。
如果你還維護運行在 JDK6 上的系統,從大檔、大欄位擷取大量小字串時要特別小心,盡量避免長期持有 substring 的結果,或用拼接、new String(...) 等方式截斷引用。而在 JDK7 以後(包含後續所有版本),這個問題已被修正,不必再 workaround。