O'Reilly logo

ASP.NET 2.0 Cookbook, 2nd Edition by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

19.2. Speeding Up String Concatenation with a StringBuilder

Problem

You want to reduce the time spent concatenating strings in an application that performs this operation repeatedly.

Solution

Concatenate strings with a StringBuilder object instead of the classic & and + concatenation operators.

Examples 19-4, 19-5 through 19-6 show the .aspx file and the VB and C# code-behind files for our application that demonstrates the performance difference between using the classic string operators and a StringBuilder object to perform concatenation. Our example concatenates two strings repeatedly and calculates the average time per concatenation for the two approaches. The output of the application is shown in Figure 19-1.

Measuring string concatenation performance output

Figure 19-1. Measuring string concatenation performance output

Discussion

In the CLR, strings are immutable, which means that once they have been created they cannot be changed. If you concatenate the two strings, str1 and str2, shown in the following code fragment, the resulting value of str1 will be 1234567890:


	str1 = "12345"
	str2 = "67890"
	str1 = str1 & str2

	str1 = "12345";
	str2 = "67890";
	str1 = str1 + str2;

The way in which this concatenation is accomplished may come as a bit of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required