String vs. StringBuilder

后端 未结 24 1521
眼角桃花
眼角桃花 2020-11-22 06:22

I understand the difference between String and StringBuilder (StringBuilder being mutable) but is there a large performance difference

24条回答
  •  余生分开走
    2020-11-22 06:38

    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.

提交回复
热议问题