String Interning
Elan Meng investigates the behaviours of string constants, interning and == compared to .equals. Very informative. The question remaining is, why would anyone ever use == instead of .equals on a String considering how likely it is to cause confusion and the potential for disaster if one of the strings for some reason isn’t interned. The answer is performance.
In the average case, the performance difference between == and .equals is pretty much non-existent. The first thing .equals does (like any good equals method) is check if the objects are == and returns true immediately if they are. The second thing .equals does is check that the strings have the same length (in Java the length of the string is a constant field and so requires no computation). If an answer still hasn’t been found, the characters of each String are iterated over and as soon as they differ, false is returned.
Now, consider the possible cases:
- The strings are .equals and == (the same object).
- The strings are .equals but not ==.
- The strings are neither .equals or == and have different lengths.
- The strings are neither .equals or == and have the same length.
- The == check returns true. The only extra cost of using .equals over == is the cost of the method call (which is likely to be inlined anyway).
- The == check will fail, the length will match and all characters in the array will have to be iterated over.
- The == check will fail, the length will be different and .equals can then return false. The only extra overhead is then the method call, and an integer comparison.
- The == check will fail, the length check will pass and the .equals method will have to iterate over each character until the first difference.

August 16th, 2004 at 9:55 pm
The one thing that has always stopped me from doing this was: interning must use some global lock.
So, while interning would cause little to no harm for desktop application it is likely to introduce extra synchronization bottleneck for server applications.
Thus potentially degrading perfromance on some multi-cpu beast.
Would you agree with this, Adrian?
May 10th, 2007 at 7:14 pm
[...] String Interning [...]