Memory usage of substrings in Java 6 and Java 7
At first glance, you may be wondering why a String object holds an offset and length of the array: why isn’t the string’s content just the whole of the char array? The answer is that when you create a substring of an existing String, the newly created substring is a new String object but which points back to the same char array as the parent (but with different offset and length). Depending on your usage, this is either a good or a bad thing:
if you keep on to the parent string after creating the substring, then you will save memory overall;
if you throw away the parent string after creating the substring, then you will waste memory (if the substring is shorter than the parent).
For example, in the following code:
click String str = “Some longish string…”;
str = str.substring(5, 4);
you might have expected the underlying char array of str to end up containing four characters. In fact, it will continue to contain the full sequence Some longish string…, but with the internal offset and length set accordingly. If this memory wastage is a problem (because we are hanging on to lots of strings created in the above manner), then we can create a new string:
see String str = “Some longish string…”;
str = new String(str.substring(5, 4));
Creating a “brand new” string like this will force the String to take up the “minimum” amount of memory as outlined above by making the underlying char array “just big enough” for the characters of the substring.
In Java 7 this design has changed as it can lead to outofmemory issues as full copy was being maintained when you might be actually referring to small substring only. f you have a VERY long string, but you only need a small part each time by using substring(). This will cause a performance problem since you need only a small part, you keep the whole thing. In Java7 full copies of exact length will be maintained for each substring