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

后端 未结 7 1416
轻奢々
轻奢々 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

    Sometimes it's worth looking at the documentation:

    The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the 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.

    In your example, there is only a single concatenation per output string, so StringBuilder gains you nothing. You should use StringBuilder in cases where you are adding to the same string many times, e.g.:

    stringOut = ...
    for(...)
        stringOut += "."
        stringOut += string2
    

提交回复
热议问题