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

Example 16-4 through Example 16-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 then calculates the average time per concatenation for the two approaches. The output of the application is shown in Figure 16-1.

Measuring string concatenation performance output

Figure 16-1. Measuring string concatenation performance output

Discussion

In the common language runtime (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 is “1234567890”.

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

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

The way in which this concatenation is ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.