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

Get ASP.NET Site Performance Secrets 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.