Refactorings that work with strings – Use StringBuilder
In addition to the refactorings that work with the concatenated strings and the String.Format call, there is another useful refactoring called Use StringBuilder. This refactoring replaces the string concatenation operations with corresponding methods of the StringBuilder class.
Using the StringBuilder class may improve the performance of the string concatenation operations. The performance of these operations depends on how often a memory allocation occurs. A usual string concatenation operation always allocates memory, and a StringBuilder concatenation operation , on the other hand, only allocates memory if the size of the StringBuilder object’s buffer is not enough to store the new data. This means that the String class is preferable for the concatenation operation of a fixed number of strings. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated. For example, when you don’t have a loop, generally you should avoid StringBuilder. There is a lot of logic in the StringBuilder class that will be slow on small string operations and it can make your code more cumbersome.
However, there is another benefit of using the StringBuilder class in regard to the memory consumption. The more temporary objects created, the more often the .NET Garbage Collector runs. The StringBuilder class creates fewer temporary objects than the usual string concatenation operations, and therefore adds less memory pressure.
The Use StringBuilder refactoring uses the appropriate Append, Insert, AppendFormat calls of the StringBuilder class when it is applied on a selected piece of strings concatenations code. It can also recreate an instance of the StringBuilder, if necessary. For example, consider the following code:
This method formats a new system audit message initializing it to an initial message, adding a new caption and additional data, such as a user name, operation name and the time taken by an operation. The code can be optimized to use the StringBuilder class. To apply it, select the string operations and the string declaration you would like to convert (you will see the preview hint of the resulting code changes):
The resulting code will look like this:
If you select a part of the code like this:
You will get the corresponding code for the selected block of code:
This code is much easier to read and maintain. It will perform much faster, especially if the data array passed to the method has many items.
Also, refer to other refactorings that work with strings.
—– Products: Refactor! Pro Versions: 11.1 and up VS IDEs: any Updated: Dec/02/2011 ID: R037