Skip navigation

StringBuilder

The Irresistible Class Meets the Immutable Object

Sharp Shooter

TECHNOLOGIES: .NET Framework | ASP.NET

LANGUAGES: C#

 

StringBuilder

The Irresistible Class Meets the Immutable Object

 

By Mike Amundsen

 

One of the .NET Framework s powerful new classes is StringBuilder. It can be used to manipulate strings in memory, including to append, insert, remove, and replace portions of string variables. By itself, this ability is no great breakthrough. All language platforms have some method for doing this essential string work. However, the StringBuilder class is designed to handle strings very efficiently.

 

In this article, I ll explain how one of the basic properties of string storage, referred to as immutability in the .NET Framework, makes string manipulation with the StringBuilder class many times more effective than working with strings directly. I ll also explain how to use methods in the StringBuilder class to append and format new strings, and I ll cover how to insert, replace, and remove portions of the string in memory.

 

Immutability and String Memory

One of the fundamental properties of memory storage in the .NET environment is that all string memory is immutable. That means the memory storage is unchangeable. Technically, you can never actually change the contents of a string variable. Instead, any time you alter the value of a string variable, the old memory is destroyed, and a new location in memory is created with the new contents. For example, this code changes the contents of a string variable:

 

string x;

x = "start";

x = "end";

 

You might imagine the value of x would be stored in a single location in the computer (such as position 1000 in memory) and that the contents at that location would update based on the code. That way, location 1000 first would contain nothing, then contain start , and then contain end . In fact, that is not the case. Because the run time cannot alter the contents of string memory, the computer must create an entirely new string in a new location every time you alter the value of x. Thus, the code above would result in location 1000 containing , a new location (1010) containing start , and a third location (1020) containing end .  The computer creates new string memory and constantly changes the memory location to which x is pointing. This is effective but not very efficient.

 

The StringBuilder class works quite differently. When you create an instance of the StringBuilder class, you actually are identifying a block of string memory whose contents can be altered successfully. In other words, the StringBuilder class treats string memory just how most of us would expect: It alters string memory instead of creating new locations for the same variable. This ability to modify memory gives StringBuilder a clear speed advantage when compared with traditional string-memory handling.

 

Here s a simple code example that shows you how much faster StringBuilder can be when compared with typical string handling. For example, say there s an ASP.NET page that has two buttons and two labels. Pressing the first button executes a 10,000-cycle loop that builds a single string and displays it in the label on the page. As you might guess, this takes some time. In my tests on my Dell laptop, the first loop (see FIGURE 1) takes about five seconds to complete.

 

void stAppend_click(object sender, EventArgs args) {

 

    string st="";

    st+=System.DateTime.Now;

    st+="
";

 

    for (int i=0;i<10000;i++) {

        st+=i.ToString();

        st+=",";

    }

    st+="
";

    st+=System.DateTime.Now;

 

    stAppendResults.Text=st;

}

FIGURE 1: Processing 10,000 string updates using typical methods can take up to five seconds.

 

Now, look at the same 10,000-cycle loop executed using an instance of the StringBuilder class. As you can see in FIGURE 2, the only difference is the use of the StringBuilder class. But, this time, my laptop can complete the loop in less than one second. That s quite a difference.

 

void sbAppend_click(object sender, EventArgs args) {

 

    System.Text.StringBuilder sb =

     new System.Text.StringBuilder();

    sb.Append(System.DateTime.Now);

    sb.Append("
");

 

    for (int i=0;i<10000;i++) {

        sb.Append(i);

        sb.Append(",");

    }

    sb.Append("
");

    sb.Append(System.DateTime.Now);

 

    sbAppendResults.Text=sb.ToString();

}

FIGURE 2: Processing 10,000 string updates using StringBuilder can take less than one second.

 

Using Append and AppendFormat

The two most commonly used methods of the StringBuilder class are the Append and AppendFormat methods. You can use them to build strings quickly and efficiently for display. As you would expect, you can use the Append method simply to add new values to the string space. However, the Append method is also smart. For example, you can use the Append method to add any type to the string space, not just string types. This means you don t need to convert numeric or date types into strings before adding them to your string space.

 

The code snippet below shows a series of variables of several types being initialized. These will be used in a StringBuilder object to create a single string for display:

 

// declare some variable types

bool            a = false;

int             b = 13;

double          c = 99999.99;

System.DateTime d = System.DateTime.Now;

string          e = "Amundsen";

 

You can use the Append method simply to add the contents of each variable to the string space, no matter what type of variable it is. For example if sb is an instance of StringBuilder and a is an instance of a bool type variable, the following code will produce the string false on the screen:

 

bool a = false;

System.Text.StringBuilder sb =

 new System.Text.StringBuilder();

sb.Append(a);

Response.Write(sb.ToString());

 

You also can use the AppendFormat method to append various data types to the string space and, at the same time, format the output. For example, if a is an instance of a double type variable set to 99999.99, then you can use an instance of StringBuilder (sb) to append a currency-formatted version of the data to the string space. The following code then would display $99,999.99:

 

double a = 99999.99;

System.Text.StringBuilder sb =

 new System.Text.StringBuilder();

sb.AppendFormat("{0:c}",a);

Response.Write(sb.ToString());

 

FIGURE 3 shows a complete example that uses both Append and AppendFormat to create strings to display.

 

<%@ page

 description="string builder append and appendformat demo"%>

<%@ import namespace="System.Text" %>

 

 

Using Append and AppendFormat with StringBuilder


   Append:

   

   AppendFormat:

   

FIGURE 3: Using the Append and AppendFormat methods to illustrate the power of the StringBuilder class.

 

Capacity Monitoring

You also can use properties and methods of StringBuilder to monitor and modify the current capacity of the string space. You can set the Capacity property to control the maximum length of the string space. You also can pass the initial capacity value when you instantiate the class. In addition, you can use the EnsureCapacity method to adjust the string-space allocation automatically to hold the new data. FIGURE 4 illustrates how you can use both the Capacity and EnsureCapacity to manage memory allocation for an instance of the StringBuilder class. You can see that the Capacity property is used to set the initial storage capacity of the StringBuilder object. The EnsureCapacity method is also used in FIGURE 4. This allows you to attempt to update the storage capacity of the StringBuilder object. If that setting fails and throws an error, you can use a try...catch block to recover from the error.

 

void submit_click(object sender, EventArgs args) {

    int inputLength = txtInput.Text.Length;

 

    // create an instance and set the initial length

    StringBuilder sb = new StringBuilder();

    sb.Capacity = 20;

 

    // make sure you have enough room

    try {

        sb.EnsureCapacity(txtInput.Text.Length);

    }

    catch (Exception exc) {

        results.Text = exc.Message;

        return;

    }

 

    // add the contents to the stringbuilder object

    try {

        sb.Append(txtInput.Text);

        results.Text = "append successful.";

    }

    catch (Exception exc) {

        results.Text = exc.Message;

    }

 

    // print out stats on the object

    lbl.Text =  "String...   : "+sb.ToString()+"
";

    lbl.Text += "Length...   : "+

     sb.Length.ToString()+"
";

    lbl.Text += "Capacity    : " +

     sb.Capacity.ToString()+"
";

    lbl.Text += "MaxCapacity.: " +

     sb.MaxCapacity.ToString()+"
";

}

FIGURE 4: Exploring the capacity-monitoring methods of StringBuilder.

 

Inserting and Removing Values

The StringBuilder class has powerful methods for inserting and removing portions of the string space. For example, the Insert method takes a starting location and a value to insert. For example, to insert the word new into the string There is text here. , you could use the following code:

 

sb.Append("There is text here.");

sb.Insert(9,"new ");

 

The Remove method takes a starting location and a length of the string block to remove. You can use the code below to remove the word new from the modified string:

 

sb.Remove(9,4);

 

FIGURE 5 shows an ASP.NET page that allows users to insert and remove strings interactively in the allocated string space.

 


FIGURE 5: Inserting and removing values with StringBuilder.

 

In FIGURE 6, you ll find the click event for the submit button shown in FIGURE 5.

 

void submit_click(object sender, EventArgs args) {

 

try {

  if (action.SelectedItem.Value=="Insert") {

    sb.Insert(Int32.Parse(txtLocation.Text),txtString.Text);

    sbContents.Text=sb.ToString();

  }

 

  if (action.SelectedItem.Value=="Remove") {

  sb.Remove(Int32.Parse(txtLocation.Text),

   Int32.Parse(txtLength.Text));

  sbContents.Text=sb.ToString();

  }

}

catch (Exception exc) {

  msg.Text=exc.Message;

}

 

}

FIGURE 6: The server-side code for inserting and removing text in a StringBuilder class.

 

Replacing Values

Finally, you also can use the Replace method to mass-replace values in the string space. For example, you can replace all the instances of Mike in the sentence below with the word Paul:

 

sb.Append("Mike is ready to start. Mike is fully prepared, too.");

sb.Replace("Mike","Paul");

 

Executing this code will result in the string Paul is ready to start. Paul is fully prepared, too.

 

You also can set a range for the Replace method. This allows you to set the starting point and complete length of the area in which to perform the replacement. In the following code, sb becomes Paul is ready to start. Mike is fully prepared, too. :

 

sb.Append("Mike is ready to start. Mike is fully prepared, too.");

sb.Replace("Mike","Paul",0,20);

 

FIGURE 7 shows an interactive ASP.NET page that allows users to replace values in an existing string.

 


FIGURE 7: Replacing values with StringBuilder.

 

Conclusion

String storage in the .NET environment is immutable: It cannot be changed, and the StringBuilder class offers a much more efficient way to manipulate strings than the methods typically used with strings. In this article, I described how to use Append and AppendFormat to build strings from various data types. I also covered how to manage the size of the allocated string space using the Capacity property and the EnsureCapacity method. Finally, you learned how to use the Insert, Remove, and Replace methods to alter the contents of the string space.

 

The files associated with this article are available for download.

 

Mike Amundsen is currently the president, chief cook, and bottle-washer at http://www.EraServer.NET, a .NET hosting and XML Web Services company. He also heads a consulting firm, http://www.Amundsen.com that enables clients to efficiently design, code, implement, and maintain successful .NET solutions. A well-known author and lecturer, Mike continues to travel the world teaching and speaking on .NET development issues. His latest book, with Paul Litwin, is ASP.NET for Developers from SAMS. He is also working on the fourth edition of Teach Yourself Database Programming with Visual Basic .NET in 21 Days and has more than a dozen other book titles to his credit. When he s not in the server room or on the road, Mike spends time with his family in and around their home in Northern Kentucky. Readers may contact Mike at mailto:[email protected].

 

Tell us what you think! Please send any comments about this article to [email protected]. Please include the article title and author.

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish