Total .NET Analyzer Rule Documentation  

StringAddition Rule

Consider using the StringBuilder class in place of the string concatenation operator.

Remarks

In .NET, there has been a significant change in the way strings are handled. .NET strings are immutable (that is, they cannot be changed at run time). When you try to manipulate a string at runtime (for instance, using the concatenation operator + ), the compiler actually creates and returns a new string without touching the original. If the size of strings or the amount of string manipulation in the application is significant, this can cause severe performance problems. In such cases, you should consider using the methods available in the StringBuilder class to manipulate strings.

Note, however, that this is not an absolute rule. If the application uses relatively small strings, or performs only a small number of concatenation operations, concatenation operator ( + ) may not represent a noticeable performance problem. In some cases, the ease of using the concatenation operator might outweigh the slight performance advantage of the StringBuilder class. Rather than replacing all string concatenation operations with the StringBuilder class, determine on a case-by-case basis whether or not it is necessary.

The following article shows performance test results that may help you determine whether or not to replace the concatenation operator:
http://aspalliance.com/remas/ASP.NET/Performance/Concatenation/

(Note that these tests were neither performed nor verified by FMS, and are in no way intended to suggest results that you may experience on your system.)

Resolution

Review string concatenation operations in the application and determine whether or not they represent a performance problem. If the size of the string or the number of concatenation operations is significant, consider using the StringBuilder class rather than the string concatenation operator ( + ).

For example, in Visual Basic, you would change:

wholeString= wholeString + newString

To use the StringBuilder class:

Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder(wholeString)
sb.Append(newString)

In C#, you would change:

wholeString= wholeString + newString;

To use the StringBuilder class:

System.Text.StringBuilder sb = new System.Text.StringBuilder(wholeString);
sb.Append(newString);

In addition, if you are concatenating multiple strings, you should include them all in one expression if possible. This allows the compiler to modifying the string in place, increasing speed and efficiency.

See Also

Using The StringBuilder Class