At what point does using a StringBuilder become insignificant or an overhead?

后端 未结 7 1411
轻奢々
轻奢々 2020-12-03 14:17

Recently I have found myself using StringBuilder for all string concatenations, big and small, however in a recent performance test I swapped out a colleague\'s stringOu

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 14:38

    The rule that I follow is -

    Use a StringBuilder when the number of concatenations is unknown at compile time.

    So, in your case each StringBuilder was only appending a few times and then being discarded. That isn't really the same as something like

    string s = String.Empty;
    for (int i = 0; i < 10000; ++i)
    {
        s += "A";
    }
    

    Where using a StringBuilder would drastically improve performance because you would otherwise be constantly allocating new memory.

提交回复
热议问题