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
?
I compared four different approach to compare the performance. I exactly don't know what happens to gc, but the important thing for me is time. Compiler is important factor here.I used jdk1.8.0_45 under window8.1 platform.
In most cases, you won't see an actual difference between the two approaches, but it's easy to construct a worst case scenario like this one:
The output is:
The problem is that to += append to a string reconstructs a new string, so it costs something linear to the length of your strings (sum of both).
So - to your question:
The second approach would be faster, but it's less readable and harder to maintain. As I said, in your specific case you would probably not see the difference.
In Java 9 the version 1 should be faster because it is converted to
invokedynamic
call. More details can be found in JEP-280:For simple strings like that I prefer to use
In order, I would say the preferred method of constructing a string is using StringBuilder, String#concat(), then the overloaded + operator. StringBuilder is a significant performance increase when working large strings just like using the + operator is a large decrease in performance (exponentially large decrease as the String size increases). The one problem with using .concat() is that it can throw NullPointerExceptions.
Apache Commons-Lang has a ToStringBuilder class which is super easy to use. It does a nice job of both handling the append-logic as well as formatting of how you want your toString to look.
Will return output that looks like
com.blah.YourClass@abc1321f[a=whatever, b=foo]
.Or in a more condensed form using chaining:
Or if you want to use reflection to include every field of the class:
You can also customize the style of the ToString if you want.
I also had clash with my boss on the fact whether to use append or +.As they are using Append(I still cant figure out as they say every time a new object is created). So I thought to do some R&D.Although I love Michael Borgwardt explaination but just wanted to show an explanation if somebody will really need to know in future.
and disassembly of above class comes out as
From the above two codes you can see Michael is right.In each case only one SB object is created.