String vs. StringBuilder

后端 未结 24 1715
眼角桃花
眼角桃花 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:35

    StringBuilder reduces the number of allocations and assignments, at a cost of extra memory used. Used properly, it can completely remove the need for the compiler to allocate larger and larger strings over and over until the result is found.

    string result = "";
    for(int i = 0; i != N; ++i)
    {
       result = result + i.ToString();   // allocates a new string, then assigns it to result, which gets repeated N times
    }
    

    vs.

    String result;
    StringBuilder sb = new StringBuilder(10000);   // create a buffer of 10k
    for(int i = 0; i != N; ++i)
    {
       sb.Append(i.ToString());          // fill the buffer, resizing if it overflows the buffer
    }
    
    result = sb.ToString();   // assigns once
    

提交回复
热议问题