Why does appending “” to a String save memory?

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

    I think this.smallpart kept referencing towards data, but why?

    Because Java strings consist of a char array, a start offset and a length (and a cached hashCode). Some String operations like substring() create a new String object that shares the original's char array and simply has different offset and/or length fields. This works because the char array of a String is never modified once it has been created.

    This can save memory when many substrings refer to the same basic string without replicating overlapping parts. As you have noticed, in some situations, it can keep data that's not needed anymore from being garbage collected.

    The "correct" way to fix this is the new String(String) constructor, i.e.

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

    BTW, the overall best solution would be to avoid having very large Strings in the first place, and processing any input in smaller chunks, aa few KB at a time.

提交回复
热议问题