Why does appending “” to a String save memory?

前端 未结 9 1825
粉色の甜心
粉色の甜心 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:08

    In Java strings are imutable objects and once a string is created, it remains on memory until it's cleaned by the garbage colector (and this cleaning is not something you can take for granted).

    When you call the substring method, Java does not create a trully new string, but just stores a range of characters inside the original string.

    So, when you created a new string with this code:

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

    you actually created a new string when you concatenated the result with the empty string. That's why.

提交回复
热议问题