October 2010
Intermediate to advanced
456 pages
10h 16m
English
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 ...
Read now
Unlock full access