Search code examples
javaperformancestringgarbage-collection

Garbage collection behaviour for String.intern()


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 ?


Solution

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

    Prior to Java 7 interned strings were allocated in PermGen space. This would 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. From Java 7 onward the interned strings are allocated on the Heap and are subject to garbage collection.

    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.