Short answer: StringBuilder
is appropriate in cases where you are concatenating an arbitrary number of strings, which you don't know at compile time.
If you do know what strings you're combining at compile time, StringBuilder
is basically pointless as you don't need its dynamic resizing capabilities.
Example 1: You want to combine "cat", "dog", and "mouse". This is exactly 11 characters. You could simply allocate a char[]
array of length 11 and fill it with the characters from these strings. This is essentially what string.Concat
does.
Example 2: You want to join an unspecified number of user-supplied strings into a single string. Since the amount of data to concatenate is unknown in advance, using a StringBuilder
is appropriate in this case.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…