String Benchmarks in C# - Refactoring for Speed/Maintainability

后端 未结 10 1405
无人及你
无人及你 2021-02-09 21:29

I\'ve been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler\'s book Refactoring: Improving the Design of Ex

10条回答
  •  不思量自难忘°
    2021-02-09 22:11

    In C# (.Net, really) When you append a string there are several things going on in the background. Now, I forget the specifics, but it is something like:

    string A = B + C;

    A += D; A += E;

    // ... rinse-repeat for 10,000 iterations

    For each line above, .NET will: 1) Allocate some new memory for A. 2) Copy the string B into the new memory. 3) Extend the memory to hold C. 4) Append the string C to A.

    The longer the string A, the more time this takes. Add to that, the more times you do this, the longer A gets, the exponentially longer this takes.

    However, with StringBuilder you are not allocating new memory, thus you skip that problem.

    If you say :

    StringBuilder A = new StringBuilder();
    A.Append(B);
    A.Append(C);
    // .. rinse/repeat for 10,000 times...
    
    string sA = A.ToString();
    

    StringBuilder (Edit: fixed description) has a string in memory. It doesn't need to re-allocate the entire string for each added sub-string. When you issue ToString(), the string is already appended in the proper format.

    One shot instead of a loop that takes an increasingly longer period.

    I hope that helps answer the WHY it took so much less time.

提交回复
热议问题