Garbage collection behaviour for String.intern()

前端 未结 4 1619
北恋
北恋 2020-11-27 07:31

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 me

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 07:37

    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).

    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.

提交回复
热议问题