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

后端 未结 7 1385
轻奢々
轻奢々 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:51

    From MSDN:

    [T]he String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.

    I guess the answer is "it depends" - if you're concatenating inside a loop with more than a handful of iterations then a StringBuilder will almost always deliver better performance, but the only way to know for sure is to actually profile.

    0 讨论(0)
提交回复
热议问题