Why does .NET create new substrings instead of pointing into existing strings?

后端 未结 5 1316
别跟我提以往
别跟我提以往 2021-01-02 11:35

From a brief look using Reflector, it looks like String.Substring() allocates memory for each substring. Am I correct that this is the case? I thought that woul

5条回答
  •  醉酒成梦
    2021-01-02 12:29

    One reason why most languages with immutable strings create new substrings rather than refer into existing strings is because this will interfere with garbage collecting those strings later.

    What happens if a string is used for its substring, but then the larger string becomes unreachable (except through the substring). The larger string will be uncollectable, because that would invalidate the substring. What seemed like a good way to save memory in the short term becomes a memory leak in the long term.

提交回复
热议问题