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 ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.