O'Reilly logo

ASP.NET Cookbook 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

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

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