Search code examples
javaconcatenationstringbuilder

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


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?


Solution

  • 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!