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
?
Since Java 9, simple one line concatenation with "+" produces code potentially better than StringBuilder.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With