2
A
回答
3
新的String(S)可以幫助garbase集合:
String huge = ...;
String small = s.substring(0,2); //huge.value char[] is not garbage collected here
String gcFriendly = new String(small); //now huge.value char[] can be garbage collected
15
從API文檔:
Unless an explicit copy of original is needed, use of this constructor is
unnecessary since Strings are immutable.
我能想到的唯一原因是在情況:
- 你已經創建了一個非常大的
String
:A. - 你」已經創建了一個小的子字符串:B基於A.如果你看看
substring
的實現,你會看到它引用相同的char []數組作爲原始字符串。 String
A已超出範圍,你想減少內存消耗。- 創建B的一個明確的副本將意味着副本:B」不再引用大
char[]
。允許B超出範圍將允許垃圾收集器收回支持A和B的大char[]
,僅留下小的char[]
支持B'。
0
以防萬一你需要的字符串是不一樣的,但相等的。
也許爲了確保測試,人們確實做了str.equals(str2)
而不是(str == str2)
。但我從不需要它。
重複http://stackoverflow.com/questions/334518/java-strings-string-s-new-stringsilly的? – VonC 2009-11-26 12:04:07
Dupe:http://stackoverflow.com/questions/390703/what-is-the-purpose-of-the-expression-new-string-in-java,http://stackoverflow.com/questions/465627/use -of-the-stringstring-constructor-in-java – 2009-11-26 12:04:08