Why does appending “” to a String save memory?

前端 未结 9 1827
粉色の甜心
粉色の甜心 2020-11-28 17:34

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 =          


        
相关标签:
9条回答
  • 2020-11-28 18:28

    When you use substring, it doesn't actually create a new string. It still refers to your original string, with an offset and size constraint.

    So, to allow your original string to be collected, you need to create a new string (using new String, or what you've got).

    0 讨论(0)
  • 2020-11-28 18:28

    Just to sum up, if you create lots of substrings from a small number of big strings, then use

       String subtring = string.substring(5,23)
    

    Since you only use the space to store the big strings, but if you are extracting a just handful of small strings, from losts of big strings, then

       String substring = new String(string.substring(5,23));
    

    Will keep your memory use down, since the big strings can be reclaimed when no longer needed.

    That you call new String is a helpful reminder that you really are getting a new string, rather than a reference to the original one.

    0 讨论(0)
  • 2020-11-28 18:32

    As documented by jwz in 1997:

    If you have a huge string, pull out a substring() of it, hold on to the substring and allow the longer string to become garbage (in other words, the substring has a longer lifetime) the underlying bytes of the huge string never go away.

    0 讨论(0)
提交回复
热议问题