I understand the difference between String
and StringBuilder
(StringBuilder
being mutable) but is there a large performance difference
A simple example to demonstrate the difference in speed when using String
concatenation vs StringBuilder
:
System.Diagnostics.Stopwatch time = new Stopwatch();
string test = string.Empty;
time.Start();
for (int i = 0; i < 100000; i++)
{
test += i;
}
time.Stop();
System.Console.WriteLine("Using String concatenation: " + time.ElapsedMilliseconds + " milliseconds");
Result:
Using String concatenation: 15423 milliseconds
StringBuilder test1 = new StringBuilder();
time.Reset();
time.Start();
for (int i = 0; i < 100000; i++)
{
test1.Append(i);
}
time.Stop();
System.Console.WriteLine("Using StringBuilder: " + time.ElapsedMilliseconds + " milliseconds");
Result:
Using StringBuilder: 10 milliseconds
As a result, the first iteration took 15423 ms while the second iteration using StringBuilder
took 10 ms.
It looks to me that using StringBuilder
is faster, a lot faster.