Skip to main content

Posts

Showing posts with the label string-interning

String.intern() vs manual string-to-identifier mapping?

I recall seeing a couple of string-intensive programs that do a lot of string comparison but relatively few string manipulation, and that have used a separate table to map strings to identifiers for equality efficiency and memory use, e.g.: public class Name { public static Map<String, Name> names = new SomeMap<String, Name>(); public static Name from(String s) { Name n = names.get(s); if (n == null) { n = new Name(s); names.put(s, n); } return n; } private final String str; public Name(String str) { this.str = str; } @Override public String toString() { return str; } // equals() and hashCode() are not overridden! } I'm pretty sure one of those program was javac from OpenJDK, so not some toy application. Of course the actual class was more complex (and also I think it implemented CharSequence), but you get the idea; the entire program was littered with Name in any location you would