String Addition in .NET

Provided by Molly Pell, Senior Systems Analyst

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.


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 ( + ).

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 modify the string in place, increasing speed and efficiency.

This tip and more detected for you with Total .NET Analyzer!


Additional Resources

 

 

Thank you! Thank you! I just finished reading this document, which was part of a link in the recent Buzz newsletter. I have printed it for others to read, especially those skeptical on the powers of Access and its capabilities.

Darren D.


View all FMS products for Microsoft Access All Our Microsoft Access Products

 

 

Free Product Catalog from FMS