Should StringBuilder.append() be always preferred than concatenation?

Viewed 109

I have some code like this:

StringBuilder rgba = new StringBuilder();  
for (...){
....
rgba.append(value + ", ");
}

IntelliJ shows me the following warning:

string concatenation as argument to 'stringbuilder.append()' call

From here, here and other sources I understand that concatenation is actually creates a new String object and that negates the whole point of using a StringBuilder.
So IntelliJsuggests me to use

rgba.append(value);
rgba.append(", ");  

instead of

rgba.append(value + ", ");  

But will this really be better?
Will this code be clearer?
Will this make the execution faster?

3 Answers

as per IntelliJ reasoning:

Reports String concatenation used as the argument to StringBuffer.append(), StringBuilder.append() or Appendable.append(). Such calls may profitably be turned into chained append calls on the existing StringBuffer/Builder/Appendable, saving the cost of an extra StringBuffer/Builder allocation. This inspection ignores compile time evaluated String concatenations, which when converted to chained append calls would only worsen performance.

so, I would say: go for it!

What you've said is correct in the sense that a mixture of concatenation and StringBuilder goes against the point of using it in theory, but the extra performance we're talking about is incredibly minimal unless you're loop has a massive number of iterations.

In terms of code clarity I think the double append is actually a lot clearer considering you're using it anyway.

I would see the two statements as

Append ", " appended on "value"
Append "value"
Append ", "

of which the second actually seems more concise, even if the code is technically longer.

In my opinion concatenation is much more readable for developers but StringBuilder.append is performant

Related