+= is often mentioned bad to use in a loop. But how bad is it?

consider the following code:

            Stopwatch watch1 = new Stopwatch();
            Stopwatch watch2 = new Stopwatch();
            String s1 = "";
            String s2 = "";
            int count = 20000;
            watch1.Start();
            for (int i = 0; i < count; i++)
            {
                s1 += i.ToString();
            }
            watch1.Stop();
            Console.WriteLine(watch1.ElapsedMilliseconds);

            watch2.Start();
            StringBuilder sb = new StringBuilder(s2);
            for (int i = 0; i < count; i++)
            {
                sb.Append(i.ToString());
            }
            s2 = sb.ToString();
            watch2.Stop();
            Console.WriteLine(watch2.ElapsedMilliseconds);

Result:
watch1: 2206
watch2: 7

wow…it seems really bad…

more on String Concatenation in C#

Advertisements