String.intern() 的垃圾收集行为
如果我使用 String.intern() 来提高性能,因为我可以使用=="来比较实习字符串,我会遇到垃圾收集问题吗?interned 字符串的垃圾回收机制与普通字符串有何不同?
If I use String.intern() to improve performance as I can use "==" to compare interned string, will I run into garbage collection issues? How does the garbage collection mechanism of interned strings differ from normal strings ?
推荐答案
其实这不是垃圾回收优化,而是字符串池优化.当您调用 String.intern()
,你用它的基本引用替换你初始字符串的引用(第一次遇到这个字符串的引用,或者这个引用,如果它还不知道的话).
In fact, this not a garbage collection optimisation, but rather a string pool optimization.
When you call String.intern()
, you replace reference to your initial String with its base reference (the reference of the first time this string was encountered, or this reference if it is not yet known).
但是,一旦您的字符串在应用程序中不再使用,它将成为垃圾收集器问题,因为实习字符串池是 String 类的静态成员,永远不会被垃圾收集.
However, it will become a garbage collector issue once your string is of no more use in application, since the interned string pool is a static member of the String class and will never be garbage collected.
根据经验,我认为最好从不使用这种实习方法,让编译器只将它用于常量字符串,声明如下:
As a rule of thumb, i consider preferrable to never use this intern method and let the compiler use it only for constants Strings, those declared like this :
String myString = "a constant that will be interned";
这更好,因为它不会让您做出错误的假设 ==
可以在它不起作用时起作用.
This is better, in the sense it won't let you do the false assumption ==
could work when it won't.
此外,事实上 String.equals
在底层调用 ==
作为优化,确保在后台使用内部字符串优化.这是 ==
不应该永远用于字符串的又一证据.
Besides, the fact is String.equals
underlyingly calls ==
as an optimisation, making it sure interned strings optimization are used under the hood. This is one more evidence ==
should never be used on Strings.
相关文章