How does StringBuilder work internally in C#?

后端 未结 4 413
醉酒成梦
醉酒成梦 2020-11-29 04:50

How does StringBuilder work?

What does it do internally? Does it use unsafe code? And why is it so fast (compared to the + opera

4条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 05:39

    StringBuilder's implementation has changed between versions, I believe. Fundamentally though, it maintains a mutable structure of some form. I believe it used to use a string which was still being mutated (using internal methods) and would just make sure it would never be mutated after it was returned.

    The reason StringBuilder is faster than using string concatenation in a loop is precisely because of the mutability - it doesn't require a new string to be constructed after each mutation, which would mean copying all the data within the string etc.

    For just a single concatenation, it's actually slightly more efficient to use + than to use StringBuilder. It's only when you're performing multiple operations and you don't really need the intermediate results that StringBuilder shines.

    See my article on StringBuilder for more information.

提交回复
热议问题