I’m tracking down a memory leak at the moment and just came across this really interesting article on how Strings are implemented in a number of different JVM’s. I haven’t come across this before, but its sure nice to know about.. Scary stuff.
http://eyalsch.wordpress.com/2009/10/27/stringleaks/
TL;DR: The backing char arrays of Strings are held on to and can’t be garbage collected, so…
Do this:
String string = "abcdefghijklmnopqrstuvqxyz";
string = new String(string.substring(2, 5));
Instead of this:
String string = "abcdefghijklmnopqrstuvqxyz";
string = string.substring(2, 5);