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

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

    Adding to the point that Strings are immutable, you should be that the following snippet will generate multiple String instances in memory.

    String s1 = "Hello", s2 = ", ", s3 = "World!";
    String res = s1 + s2 + s3;
    

    s1+s2 => new string instance (temp1)

    temp1 + s3 => new string instance (temp2)

    res is a reference to temp2.

提交回复
热议问题