Why does appending “” to a String save memory?

Doing the following:

data.substring(x, y) + ""

creates a new (smaller) String object, and throws away the reference to the String created by substring(), thus enabling garbage collection of this.

The important thing to realise is that substring() gives a window onto an existing String – or rather, the character array underlying the original String. Hence it will consume the same memory as the original String. This can be advantageous in some circumstances, but problematic if you want to get a substring and dispose of the original String (as you’ve found out).

Take a look at the substring() method in the JDK String source for more info.

EDIT: To answer your supplementary question, constructing a new String from the substring will reduce your memory consumption, provided you bin any references to the original String.

NOTE (Jan 2013). The above behaviour has changed in Java 7u6. The flyweight pattern is no longer used and substring() will work as you would expect.

Leave a Comment