How does StringBuilder work internally in C#?

后端 未结 4 416
醉酒成梦
醉酒成梦 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:48

    The StringBuilder uses a string buffer that can be altered, compared to a regular String that can't be. When you call the ToString method of the StringBuilder it will just freeze the string buffer and convert it into a regular string, so it doesn't have to copy all the data one extra time.

    As the StringBuilder can alter the string buffer, it doesn't have to create a new string value for each and every change to the string data. When you use the + operator, the compiler turns that into a String.Concat call that creates a new string object. This seemingly innocent piece of code:

    str += ",";
    

    compiles into this:

    str = String.Concat(str, ",");
    

提交回复
热议问题