-
Book Overview & Buying
-
Table Of Contents
ASP.NET Site Performance Secrets
By :
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 StringBuilder and getting its contents into a string is contained within the 1000 times loop.
On my machine, the results were:
|
Test |
Time taken (ticks) |
|---|---|
|
1000 * 20 concatenations |
29474 |
|
1000 * 20 StringBuilder appends |
11906 |
This shows...
Change the font size
Change margin width
Change background colour