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
My rule of thumb is simple.
+
.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;
...