Is String.intern() good or evil ?
There’s currently a relatively popular weblog on java.net about howto use the String intern() function to improve the performance of String comparsions.See link above.
Since String comparsions can occur very frequently, this is a valid goal. To cite the author :
So if you’re going to be comparing the same strings repeatedly, you can get a significant performance advantage by reducing it to an identity comparison rather than an equality comparison. The basic algorithm is:
1) Create a hash set of Strings
2) Check to see if the String you’re dealing with is already in the set
3) If so, return the one from the set
4) Otherwise, add this string to the set and return it
After following this algorithm, you are guaranteed that if two strings contain the same characters, they are also the same instance. This means that you can safely compare strings using == rather than equals(), gaining a significant performance advantage with repeated comparisons.
It’s true that comparisons with == are much faster, but unfortunately intern() has several drawbacks.
First it requires a lock within the VM, potentially leading to performance problems in multithreaded applications.
Second intern() is im my experience on Sun’s JDK 1.4 slower than just using a HashMap that holds the already known Strings.
Comparing two Strings with the equals method is automatically faster, if the Strings are identical, because equals first checks for identity (using == ) anyway. So you just have to take care that you don’t duplicate Strings for no good reason. I will provide more details about problems with duplicated Strings in one of my next blogs.
So my advice is for now to stay away from String.intern().