我已經開始研究字串實習,這似乎是一個很棒的功能,但是我還沒有找到為什么要使用字串建構式創建字串的充分理由,經過一番挖掘后我想出了這個,有人可以確認(或拒絕)如果這是使用new?創建字串的正當理由
假設你有 2 個字串:
String novel = "The contents of a very long novel..."
String page = new String("The contents of a single page...")
默認情況下,所有字串文字都存盤在字串池中(例如使用 String novel),默認情況下,所有子字串都novel將被保留(假設它們是作為字串文字創建的)以優化記憶體分配。使用 new 關鍵字創建字串會導致在堆上而不是在字串池中創建字串。您可能想要避免實習的一個特殊情況是,如果您想要創建一個字串,它是一個非常大的字串文字(例如page)的子字串。
例如; 假設您有一個非常大的字串文字(例如小說的內容),您只想處理其中的一部分(例如單頁)。在創建僅包含小說單頁的字串時,使用字串建構式(通過 new 關鍵字)可能是有益的。這樣,非常大的字串可以更快地從字串池中釋放出來,并且只保留包含堆上頁面內容的字串。相反,如果您創建了一個字串文字,它是整個小說的實習子字串,novel則盡管只需要小說字串的一小部分,但字串池中可能會保持較大的數量。
uj5u.com熱心網友回復:
TL;DR:在現代 JVM 中沒有充分/有效new的理由,或者顯式呼叫。StringString.intern()
您的問題包含對事實的虛假陳述,這意味著您得出的結論不正確。
默認情況下,所有字串文字都存盤在字串池中(例如使用 String
novel)
這是正確的,盡管它不是“默認情況下”。(就像說“默認情況下正方形有 4 條邊”。正方形有 4 條邊,句號。沒有例外。也沒有默認值。)
并且默認情況下,所有的子字串都
novel將被實習(假設它們被創建為字串文字)以優化記憶體分配。
不正確。
String由該方法創建的AString.substring()未被實習。不在當前的 Java 版本中,也不在任何以前的版本中。(但見下文。)
使用
new關鍵字創建字串會導致在堆上而不是在字串池中創建字串。
正確的。
您可能希望避免實習的一個特殊情況是,如果您想創建一個字串,它是一個非常大的字串文字(例如頁面)的子字串。
不正確。
我認為您將“實習”與其他內容混淆了。
實際上,在現代 JVM 中,您總是希望避免實習。它很昂貴,并且它導致字串物件(人為地)保存的時間超過了我需要的時間。
事實上,實習仍然存在的唯一真正原因是,有必要保證 JLS 中指定的關于編譯時常量字串的某些語意屬性。
現代 JVM(Java 9 及更高版本)在垃圾收集器中對存活時間足夠長的字串執行字串重復資料洗掉。這是透明地發生的......并且在它可能是有益的情況下。
歷史記錄。
In some old JVMs, there used to be a good reason to call new String in conjunction with substring. The problem was the substring method has a "clever optimization" whereby it created the substrings to share the backing char[] with the original string1. This had the problem that references to (small) substrings could keep the (large) backing array reachable. It was a subtle kind of memory leak. You could avoid the leak by using new.
However:
- The optimization was NOT interning. The substrings were created in the regular heap, and they did not have the semantics of interned strings.
- The problem only affected certain
Stringuse-cases. And in practice they didn't involve largeStringliterals. - The problem was solved long ago. The
String.substringnow creates a newStringwith its own backing array.
In summary, using new String might have been a good idea in some cases with old Java versions, but it isn't anymore. It was fixed in Java 7.
1 - Interestingly, the source code for String describes this as a speed optimization rather than a space optimization.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426709.html
下一篇:如何解決“org.openqa.selenium.support.ui.UnexpectedTagNameException:元素應該是“選擇”但是“輸入””硒錯誤
