Remix.run Logo
throeaway9 4 days ago

For cases where a string repeats itself, you can use String.intern() to reuse data.

layer8 4 days ago | parent [-]

String.intern() doesn't reuse the data per se. It merely gives you a canonical instance with the same value as the String instance you invoke it on (unless it's the first time it is invoked for that value, in which case it returns the same instance you already have in hand). At that point the latter duplicate instance has already been constructed. The only benefit in terms of memory is that the duplicate instance might be garbage-collected earlier if the program stops referencing it and uses the interned instance instead.

Also, String.intern() can be quite slow compared to something like ConcurrentHashMap.putIfAbsent().