String vs. StringBuilder

后端 未结 24 1302
眼角桃花
眼角桃花 2020-11-22 06:22

I understand the difference between String and StringBuilder (StringBuilder being mutable) but is there a large performance difference

24条回答
  •  旧时难觅i
    2020-11-22 06:50

    This benchmark shows that regular concatenation is faster when combining 3 or fewer strings.

    http://www.chinhdo.com/20070224/stringbuilder-is-not-always-faster/

    StringBuilder can make a very significant improvement in memory usage, especially in your case of adding 500 strings together.

    Consider the following example:

    string buffer = "The numbers are: ";
    for( int i = 0; i < 5; i++)
    {
        buffer += i.ToString();
    }
    return buffer;
    

    What happens in memory? The following strings are created:

    1 - "The numbers are: "
    2 - "0"
    3 - "The numbers are: 0"
    4 - "1"
    5 - "The numbers are: 01"
    6 - "2"
    7 - "The numbers are: 012"
    8 - "3"
    9 - "The numbers are: 0123"
    10 - "4"
    11 - "The numbers are: 01234"
    12 - "5"
    13 - "The numbers are: 012345"
    

    By adding those five numbers to the end of the string we created 13 string objects! And 12 of them were useless! Wow!

    StringBuilder fixes this problem. It is not a "mutable string" as we often hear (all strings in .NET are immutable). It works by keeping an internal buffer, an array of char. Calling Append() or AppendLine() adds the string to the empty space at the end of the char array; if the array is too small, it creates a new, larger array, and copies the buffer there. So in the example above, StringBuilder might only need a single array to contain all 5 additions to the string-- depending on the size of its buffer. You can tell StringBuilder how big its buffer should be in the constructor.

提交回复
热议问题