Lots of people talk about the performance advantages of String.intern(), but I\'m actually more interested in what the performance penalty may be.
My main concerns a
The following micro benchmark suggests using an enum offers around a ten times performance improvement (the usual micro benchmark caveats apply) test code as follows:
public class Test {
private enum E {
E1;
private static final Map named = new HashMap();
static {
for (E e : E.values()) {
named.put( e.name(), e );
}
}
private static E get(String s) {
return named.get( s );
}
}
public static void main(String... strings) {
E e = E.get( "E1" ); // ensure map is initialised
long start = System.nanoTime();
testMap( 10000000 );
long end = System.nanoTime();
System.out.println( 1E-9 * (end - start) );
}
private static void testIntern(int num) {
for (int i = 0; i < num; i++) {
String s = "E1".intern();
}
}
private static void testMap(int num) {
for (int i = 0; i < num; i++) {
E e = E.get( "E1" );
}
}
}
Results (10 million iterations): testIntern() - 0.8 seconds testMap() - 0.06 seconds
Of course YMMV, but enums offer so many benefits over Strings...type-safety over other random Strings, ability to add methods etc. seems the best way to go imho