String.intern() 的垃圾收集行为 [英] Garbage collection behaviour for String.intern()

查看:23
本文介绍了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.

这篇关于String.intern() 的垃圾收集行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆