O'Reilly logo

ASP.NET Site Performance Secrets by Matt Perdeck

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

StringBuilder

If you need to append a series of strings to another string in a loop, you can save CPU cycles by using a StringBuilder. This is because string += concatenations create a new string on the heap, which takes time.

Here is some test code using regular string concatenations:

for (int i = 0; i < 1000; i++)
{
string s = "";
for (int j = 0; j < 20; j++)
{
s += "aabbcc";
}
}

And here is the equivalent using a StringBuilder:

for (int i = 0; i < 1000; i++)
{
string s = "";
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 20; j++)
{
sb.Append( aabbcc );
}
s = sb.ToString();
}

Both bits of code append a string to another string 20 times. They repeat doing that a 1000 times to get some meaningful numbers. The overhead of creating the ...

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