I've read questions on SO explaining that Java automatically interns String literals, and obviously interns when intern()
is called. However, I am wondering if in a loop (a foreach
loop in my case) the Strings are also automatically interned. I ask because I am interning Strings to save memory in several very large LinkedHashMaps
and want to know if calling intern()
is redundant.
Example:
String array[] = createLargeArbitraryArray();
Map<String, Float> map = new LinkedHashMap<String, Float>(array.length);
for (String s : array)
map.put(s, 1f);
}
Would the next example have any difference in memory usage than the first (assuming same array
values), or is s
already interned at that point?
String array[] = createLargeArbitraryArray();
Map<String, Float> map = new LinkedHashMap<String, Float>(array.length);
for (String s : array)
map.put(s.intern(), 1f);
}
I realize that in this case, there may be no equivalent Strings, but in my case I have a custom key for several maps that does use duplicate String values in the end, and I am wondering if calling intern()
to save memory would be redundant or not at this point.
To add to this question, if an array was created from literals (in which case they are interned initially), then passed to a method as an argument, would a loop as above use interned Strings or not? i.e.:
/**
* @param array created from literals
*/
public void populateMap(String[] array) {
for (String s : array)
map.put(s, 1f); // Interned or not?
}
In this case, either s
is interned because array
was interned to begin with, or s
is not interned because it is declared as a new object in the loop parameters. Which is correct?
EDIT: To further explain my reasons for interning, I want to free up memory in the heap to avoid hitting the max heap size or GC overhead limit. Performance and speed are not extremely important to me in this case.