- Introduction
- Creating and Using String Objects
- Formatting Strings
- Accessing Individual String Characters
- Analyzing Character Attributes
- Case-Insensitive String Comparison
- Working with Substrings
- Using Verbatim String Syntax
- Choosing Between Constant and Mutable Strings
- Optimizing StringBuilder Performance
- Understanding Basic Regular Expression Syntax
- Validating User Input with Regular Expressions
- Replacing Substrings Using Regular Expressions
- Building a Regular Expression Library
3.9. Optimizing StringBuilder Performance
Knowing that a StringBuilder object can suffer more of a performance hit than a regular string object, you want to optimize the StringBuilder object to minimize performance issues.
Technique
Use the EnsureCapacity method in the StringBuilder class. Set this integral value to a value that signifies the length of the longest string you may store in this buffer.
Comments
The StringBuilder class contains methods that allow you to expand the memory of the internal buffer based on the size of the string you may store. As your string continually grows, the StringBuilder won't have to repeatedly allocate new memory for the internal buffer. In other words, if you attempt to place a larger length string than what the internal buffer of the StringBuilder class can accept, then the class will have to allocate additional memory to accept the new data. If you continuously add strings that increase in size from the last input string, the StringBuilder class will have to allocate a new buffer size, which it does internally by calling the GetStringForStringBuilder method defined in the System.String class. This method ultimately calls the unmanaged method FastAllocateString. By giving the StringBuilder class a hint using the EnsureCapacity method, you can help alleviate some of this continual memory reallocation, thereby optimizing the StringBuilder performance by reducing the amount of memory allocations needed to store a string value.