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

查看:100
本文介绍了String.intern()的垃圾收集行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用String.intern()来提高性能,因为我可以使用==来比较实际的字符串,我会遇到垃圾收集问题吗?实际字符串的垃圾收集机制与普通字符串有什么不同?

解决方案

实际上,这不是垃圾收集优化,而是而是一个字符串池优化。
当您调用

然而,一旦你的字符串在应用程序中不再使用,它​​将成为一个垃圾回收器问题,因为interned字符串池是静态的作为String类的成员,并且永远不会被垃圾收集。



作为一个经验法则,我认为可以选择从不使用这种实习方法,让编译器仅将它用于常量字符串,如下所示:

 字符串myString =将被实例化的常量 ; 

这样更好,从某种意义上说它不会让你做假设<$ c $



另外,事实是 String.equals code>潜在地调用 == 作为优化,这使得确定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 ?

解决方案

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 were encountered, or this reference if it is not yet known).

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.

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天全站免登陆