Wednesday, October 03, 2007
Java Substring Caveat
It is one of the commonly used function in the java String class but many people don't realize the caveat associated with it.
When you call the substring on a String object, the implementation do NOT create a new char array that is backing it but shares it. Most of the cases this does work fine except in scenarios where you have a very large original String and want to keep reference to a part of that String.
For ex.,
String originalString = "Very large string to demo the caveat with substring"; |
Java2html |
Programmer would assume that newString has occupies memory to store 9 characters but truth is that it is 51 characters. This is due to the fact that when substring is called, Java String library didn't actually create a new character array of required length but used the same one created by originalString. This isn't an issue if you continue to keep the strong reference to the originalString as newString still does share same memory space but otherwise newString is using more memory than it should.
Is there a simple solution? There is.
String newString = new String(originalString.substring(42)); |
Java2html |