Why does appending "" to a String save memory?

Posted by hsmit on Stack Overflow See other posts from Stack Overflow or by hsmit
Published on 2010-01-27T14:52:06Z Indexed on 2010/04/29 1:37 UTC
Read the original article Hit count: 435

Filed under:
|
|
|

I used a variable with a lot of data in it, say String data. I wanted to use a small part of this string in the following way:

this.smallpart = data.substring(12,18);

After some hours of debugging (with a memory visualizer) I found out that the objects field smallpart remembered all the data from data, although it only contained the substring.

When I changed the code into:

this.smallpart = data.substring(12,18)+""; 

..the problem was solved! Now my application uses very little memory now!

How is that possible? Can anyone explain this? I think this.smallpart kept referencing towards data, but why?

UPDATE: How can I clear the big String then? Will data = new String(data.substring(0,100)) do the thing?

© Stack Overflow or respective owner

Related posts about java

Related posts about memory