Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

  • Print
  • + Share This
This chapter is from the book

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:

  1. Type System.Text.StringBuilder sb where sb is the variable name.

  2. Type

    = new System.Text.StringBuilder();.

  3. Use StringBuilder's Append, Insert, Remove, and Replace functions to manipulate the string buffer.

  4. Use the ToString() function to retrieve the final contents of the buffer (Figure 4.66).

    Figure 4.66Figure 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.67Figure 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.

  • + Share This
  • 🔖 Save To Your Account