Does StringBuilder become immutable after a call to ToString?

前端 未结 5 775
面向向阳花
面向向阳花 2021-01-01 19:09

I distinctly remember from the early days of .NET that calling ToString on a StringBuilder used to provide the new string object (to be returned) with the internal char buff

5条回答
  •  醉梦人生
    2021-01-01 20:08

    Yes, you remember correctly. The StringBuilder.ToString method used to return the internal buffer as the string, and flag it as used so that additional changes to the StringBuilder had to allocate a new buffer.

    As this is an implementation detail, it's not mentioned in the documentation. This is why they can change the underlying implementation without breaking anything in the defined behaviour of the class.

    As you see from the code posted, there is not a single internal buffer any more, instead the characters are stored in chunks, and the ToString method puts the chunks together into a string.

    The reason for this change in implementation is likely that they have gathered information about how the StringBuilder class is actually used, and come to the conclusion that this approach gives a better performance weighed between average and worst case situations.

提交回复
热议问题