Check my code: StringBuilder vs. concatenation
I think I did this right, but give it a look. I'm trying to demonstrate the benefit of using StringBuilder over straight string concatenation. The two loops are functionally equivalent, right?
string sentence = "I really like riding roller coasters because they're super fun and have ups and downs, just like life!";
string[] words = sentence.Split(new char[] { ' ' });
string result = "";
Trace.Warn("Start concatenation");
for (int i = 0; i < 1000; i++)
{
foreach (string word in words)
{
result = result + word + " ";
}
}
Trace.Warn("End concatenation");
Trace.Warn("Start StringBuilder");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
foreach (string word in words)
{
builder.Append(word);
builder.Append(" ");
}
}
result = builder.ToString();
Trace.Warn("End StringBuilder");
If you're interested, the trace times looked like this:
Start concatenation | 0.000157 |
End concatenation | 22.377516 |
Start StringBuilder | 0.000212 |
End StringBuilder | 0.013082 |