Let’s assume I create the following two strings at runtime (from user input for example):
public void someMethod(String input) {
if ( input == null ) return;
String a = input + input;
String b = input;
...
}
Is Java (and its compiler) smart enough to detect at runtime that b is contained in a and therefore it is not necessary to allocate memory for b? b could just point at a with half the length?
In other words, does Java implement a dynamic version of String.intern()?
EDIT
Considering answers made so far, my example should be:
public void someMethod(String input) {
if ( input == null ) return;
String a = input + input + input;
String b = input + input;
...
}
You’re not actually creating two strings in your example:
bis just a reference toinput. So, to do what you’re asking, Java would have to somehow go back and alter old strings when a new string is created (such as by sayinginput + input).To answer your broader question, AFAIK the only way for two strings to be sharing memory (besides, as you mention, being
intern()‘d) is for one or both to have been created usingsubstring(). So if you really wanted to save on memory, you could do this:(To be clear, this will only save memory if the value of
bis being stored somewhere butinputis discarded and winds up garbage-collected.)EDIT
New and improved example for new and improved question:
(Note that this will always save memory over the second example in the question, since we’ve avoided an allocation altogether. So the previous caveat doesn’t apply.)