Daniel Rikowski Daniel Rikowski - 28 days ago 7
Java Question

Is it good practice to use java.lang.String.intern()?

The Javadoc about

doesn't give much detail. (In a nutshell: It returns a canonical representation of the string, allowing interned strings to be compared using
==
)


  • When would I use this function in favor to
    String.equals()
    ?

  • Are there side effects not mentioned in the Javadoc, i.e. more or less optimization by the JIT compiler?

  • Are there further uses of
    String.intern()
    ?


dfa dfa
Answer

When would I use this function in favor to String.equals()

when you need speed since you can compare strings by reference (== is faster than equals)

Are there side effects not mentioned in the Javadoc?

The primary disadvantage is that you have to remember to make sure that you actually do intern() all of the strings that you're going to compare. It's easy to forget to intern() all strings and then you can get confusingly incorrect results. Also, for everyone's sake, please be sure to very clearly document that you're relying on the strings being internalized.

The second disadvantage if you decide to internalize strings is that the intern() method is relatively expensive. It has to manage the pool of unique strings so it does a fair bit of work (even if the string has already been internalized). So, be careful in your code design so that you e.g., intern() all appropriate strings on input so you don't have to worry about it anymore.

(from JGuru)

Third disadvantage (Java 7 or less only): interned Strings live in PermGen space, which is usually quite small; you may run into an OutOfMemoryError with plenty of free heap space.

(from Michael Borgwardt)

Comments