The String object is immutable. Every time you use one of the methods in the
System.String class, you create a new string object in memory, which requires
a new allocation of space for that new object. In situations where you need
to perform repeated modifications to a string, the overhead associated with
creating a new String object can be costly. The System.Text.StringBuilder
class can be used when you want to modify a string without creating a new
object. For example, using the StringBuilder class can boost performance when
concatenating many strings together in a loop."
So, to answer the question, at what point is it more efficient, I wrote a
little tester. The StringBuilder returned Sub-10ms times (DateTime not
capable of registering < 10ms) at 1000 or fewer iterations of a loop simply
appending the string "string". The += method of concatenation takes 15+ms for
the same iterations. At 5000 iterations, the += method was becoming much
slower at 218ms. versus the StringBuilder which was still sub 10ms.Even at
10000 iterations, the SB was sub 10, while the concat method had gone over
1.2 seconds. My test code is as follows:
private void UpdateTime()
{
int iterations = Int32.Parse(txtIterations.Text);
string theString = txtTheString.Text;
DateTime strCall = DateTime.Now;
string targetString = null;
for(int x = 0 ; x < iterations ; x++)
{
targetString += theString;
}
TimeSpan time = (DateTime.Now - strCall);
txtConcatTime.Text = time.TotalMilliseconds.ToString();
//StringBuilder
DateTime inCall = DateTime.Now;
StringBuilder sb = new StringBuilder(theString);
for(int x = 0 ; x < iterations ; x++)
{
sb.Append(theString);
}
time = (DateTime.Now - inCall);
txtStringBTime.Text = time.TotalMilliseconds.ToString();
MessageBox.Show("done");
}
HTH
Sudhakar Sadasivuni
http://one.mvpblog.com