Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder vs String concatenation in toString() in Java

Given the 2 toString() implementations below, which one is preferred:

public String toString(){     return "{a:"+ a + ", b:" + b + ", c: " + c +"}"; } 

or

public String toString(){     StringBuilder sb = new StringBuilder(100);     return sb.append("{a:").append(a)           .append(", b:").append(b)           .append(", c:").append(c)           .append("}")           .toString(); } 

?

More importantly, given we have only 3 properties it might not make a difference, but at what point would you switch from + concat to StringBuilder?

like image 623
non sequitor Avatar asked Oct 07 '09 15:10

non sequitor


People also ask

Is StringBuilder more efficient than string concatenation Java?

Since Java 9, simple one line concatenation with "+" produces code potentially better than StringBuilder.

Which is faster string concatenation or the StringBuilder class?

Note that regular string concatenations are faster than using the StringBuilder but only when you're using a few of them at a time. If you are using two or three string concatenations, use a string.

What is the best way to concatenate strings in Java?

Using + Operator The + operator is one of the easiest ways to concatenate two strings in Java that is used by the vast majority of Java developers. We can also use it to concatenate the string with other data types such as an integer, long, etc.

Which is better string or StringBuilder?

String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.


1 Answers

Version 1 is preferable because it is shorter and the compiler will in fact turn it into version 2 - no performance difference whatsoever.

More importantly given we have only 3 properties it might not make a difference, but at what point do you switch from concat to builder?

At the point where you're concatenating in a loop - that's usually when the compiler can't substitute StringBuilder by itself.

like image 119
Michael Borgwardt Avatar answered Sep 27 '22 20:09

Michael Borgwardt