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

后端 未结 5 1314
别跟我提以往
别跟我提以往 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:18

    Because strings are immutable in .NET, every string operation that results in a new string object will allocate a new block of memory for the string contents.

    In theory, it could be possible to reuse the memory when extracting a substring, but that would make garbage collection very complicated: what if the original string is garbage-collected? What would happen to the substring that shares a piece of it?

    Of course, nothing prevents the .NET BCL team to change this behavior in future versions of .NET. It wouldn't have any impact on existing code.

提交回复
热议问题