- Preparing Your Machine to Work with Strings
- Working with Strings
- Initializing Strings
- Comparing Strings
- Concatenating Strings
- Finding the String Length
- Comparing and Concatenating Strings in the Sample Application
- Creating Strings from Characters
- Using Escape Characters
- Using Literal Strings
- Accessing the String's Characters
- Finding a Substring within a String
- Extracting Part of the String
- Splitting a String
- Joining a String
- Uppercasing and Lowercasing
- Formatting Strings
- Finishing the Sample Application
- Representing Objects as Strings
- Allocating Strings with StringBuilder
Allocating Strings with StringBuilder
Every time you manipulate a string using one of the string commands, the system silently allocates new string buffers. Say you initialize a string variable to a certain string, then you use the Concat command to add some characters to the string. The .NET runtime doesn't adjust the original string buffer; it creates a new string buffer that contains the original string plus the appended piece. Eventually, if you aren't careful, you can use up the memory for allocating objects and force the runtime to do a garbage collection. Doing a garbage collection isn't too time-consuming, but too many collections can affect the performance of your program. For that reason Microsoft created a class called StringBuilder, which lets you manipulate a single buffer of characters. You can insert, append, and remove characters from the buffer. Then, when you're done using the buffer, you use the ToString function in the class to obtain a string object from the buffer.
To create strings with StringBuilder:
Type System.Text.StringBuilder sb where sb is the variable name.
= new System.Text.StringBuilder();.
Use StringBuilder's Append, Insert, Remove, and Replace functions to manipulate the string buffer.
Use the ToString() function to retrieve the final contents of the buffer (Figure 4.66).
Figure 4.66 StringBuilder lets you manipulate the characters of a string without creating multiple string objects in memory. When you're done manipulating the string, you call the ToString method to obtain the end result.
The StringBuilder's buffer begins with enough space for 16 characters. If you go beyond 16 characters the class creates a new buffer with double its current space and fills it in with the old characters. Going beyond the capacity of StringBuilder too many times defeats the purpose of using StringBuilder because you then create multiple buffers in memory. You can minimize the number of times this happens by starting with a larger buffer (Figure 4.67).
Figure 4.67 StringBuilder's internal character buffer expands as you append characters. Too much expanding can affect performance. For that reason you can specify the initial size of the buffer. In this case the buffer is 1024 characters at the beginning. StringBuilder will only expand the buffer if you add more than 1024 characters.