5.5. StringBuilder

 < Day Day Up > 

The primary drawback of strings is that memory must be allocated each time the contents of a string variable are changed. Suppose we create a loop that iterates 100 times and concatenates one character to a string during each iteration. We could end up with a hundred strings in memory, each differing from its preceding one by a single character.

The StringBuilder class addresses this problem by allocating a work area (buffer) where its methods can be applied to the string. These methods include ways to append, insert, delete, remove, and replace characters. After the operations are complete, the ToString method is called to convert the buffer to a string that can be assigned to a string variable. Listing 5-1 introduces some of the StringBuilder methods in an example that creates a comma delimited list.

Listing 5-1. Introduction to StringBuilder
 using System; using System.Text; public class MyApp {    static void Main()    {       // Create comma delimited string with quotes around names       string namesF = "Jan Donna Kim ";       string namesM = "Rob James";       StringBuilder sbCSV = new StringBuilder();       sbCSV.Append(namesF).Append(namesM);       sbCSV.Replace(" ","','");       // Insert quote at beginning and end of string       sbCSV.Insert(0,"'").Append("'");       string csv = sbCSV.ToString();       // csv = 'Jan','Donna','Kim','Rob','James'    } } 

All operations occur in a single buffer and require no memory allocation until the final assignment to csv. Let's take a formal look at the class and its members.

StringBuilder Class Overview

Constructors for the StringBuilder class accept an initial string value as well as integer values that specify the initial space allocated to the buffer (in characters) and the maximum space allowed.

 // Stringbuilder(initial value) StringBuilder sb1 = new StringBuilder("abc"); // StringBuilder(initial value, initial capacity) StringBuilder sb2 = new StringBuilder("abc", 16); // StringBuiler(Initial Capacity, maximum capacity) StringBuilder sb3 = new StringBuilder(32,128); 

The idea behind StringBuilder is to use it as a buffer in which string operations are performed. Here is a sample of how its Append, Insert, Replace, and Remove methods work:

 int i = 4; char[] ch = {'w','h','i','t','e'}; string myColor = " orange"; StringBuilder sb = new StringBuilder("red blue green"); sb.Insert(0, ch);              // whitered blue green sb.Insert(5," ");              // white red blue green sb.Insert(0,i);                // 4white red blue green sb.Remove(1,5);                // 4 red blue green sb.Append(myColor);            // 4 red blue green orange sb.Replace("blue","violet");   // 4 red violet green orange string colors = sb.ToString(); 

StringBuilder Versus String Concatenation

Listing 5-2 tests the performance of StringBuilder versus the concatenation operator. The first part of this program uses the + operator to concatenate the letter a to a string in each of a loop's 50,000 iterations. The second half does the same, but uses the StringBuilder.Append method. The Environment.TickCount provides the beginning and ending time in milliseconds.

Listing 5-2. Comparison of StringBuilder and Regular Concatenation
 using System; using System.Text; public class MyApp {    static void Main()    {       Console.WriteLine("String routine");       string a = "a";       string str = string.Empty;       int istart, istop;       istart = Environment.TickCount;       Console.WriteLine("Start: "+istart);       // Use regular C# concatenation operator       for(int i=0; i<50000; i++)       {          str += a;       }       istop = Environment.TickCount;       Console.WriteLine("Stop: "+istop);       Console.WriteLine("Difference: " + (istop-istart));       // Perform concatenation with StringBuilder       Console.WriteLine("StringBuilder routine");       StringBuilder builder = new StringBuilder();       istart = Environment.TickCount;       Console.WriteLine("Start: "+istart);       for(int i=0; i<50000; i++)       {          builder.Append(a);       }       istop = Environment.TickCount;       str = builder.ToString();       Console.WriteLine("Stop: "+Environment.TickCount);       Console.WriteLine("Difference: "+ (istop-istart));    } } 

Executing this program results in the following output:

 String routine Start: 1422091687 Stop: 1422100046 Difference: 9359 StringBuilder routine Start: 1422100046 Stop: 1422100062 Difference: 16 

The results clearly indicate the improved performance StringBuilder provides: The standard concatenation requires 9,359 milliseconds versus 16 milliseconds for StringBuilder. When tested with loops of 1,000 iterations, StringBuilder shows no significant advantage. Unless your application involves extensive text manipulation, the standard concatenation operator should be used.

     < Day Day Up > 

    Core C# and  .NET
    Core C# and .NET
    ISBN: 131472275
    EAN: N/A
    Year: 2005
    Pages: 219

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net