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

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

    My rule of thumb is simple.

    1. If you reasonably can write a single expression that produces the final, then use +.
    2. If you can't (due either to size or variability), then use StringBuilder.

    In my experience, expressions such as:

    "Id: " + item.id + " name: " + item.name
    

    can be written and understood much more easily than:

    StringBuilder sb = new StringBuilder();
    sb.append("Id: ").append(item.id);
    sb.append(" name: ").append(item.name);
    

    (followed by using the string from sb where the above expression would have been written), and it performs equally well (hint: look at the compiled code to see why!)

    On the other hand, when there's need to accumulate a string over time (as the program runs) or space (made up of values coming from different parts of the code), in a way that is impractical to write as a single-line expression, then StringBuilder avoids the overhead (time and memory-churning) of:

    String s = somethingExpression;
    ...
    s += someOtherExpression;
    ...
    s += yetAnotherExpression;
    ...
    

提交回复
热议问题