>Hi All, sure most of you know this but I thought I'd post it anyway , I couldnt believe the speed difference, paste this code and compile as console app, then play around increasing the loops
>
>
>
>
>using System;
>using System.Text;
>
>public class Test
>{
> static void Main()
> {
> DateTime start = DateTime.Now;
> StringBuilder builder = new StringBuilder();
> for (int i = 0; i < 200000; i++)
> {
> builder.Append("!");
> }
> string x = builder.ToString();
> DateTime end = DateTime.Now;
> Console.WriteLine("Time taken: {0}", end - start);
>
> Console.WriteLine("Length of x is " + x.Length);
>
> x = "";
> start = DateTime.Now;
>
> for (int i = 0; i < 200000; i++)
> {
> x+= "!";
> }
>
> end = DateTime.Now;
> Console.WriteLine("Time taken: {0}", end - start);
> Console.WriteLine("Length of x is " + x.Length);
>
> }
>}
>
>
Pete,
It is a known thing I think and makes quite sense. In .Net string type is immutable and a new one is created when it's different. ie:
string x = "hello";
x += " there";
You'd think now in heap only there is a single string "hello there", but now there is two "hello" and "hello there". The more you create new strings the more space you eat from heap. Soon it becomes dog slow to add new ones.
StringBuilder is especially built for such cases. Whenever I need to concatanate more than a few strings I use SB.
Way back, Michel had a thread about it where he was experiencing dramatic slowdown concatanating datatable rows and SB was the answer. Check that out if you can find, there SB was used along with AppendFormat to create a big formatted string.
Cetin