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
?
There seems to be some debate whether using StringBuilder is still needed with current compilers. So I thought I'll give my 2 cents of experience.
I have a
JDBC
result set of 10k records (yes, I need all of them in one batch.) Using the + operator takes about 5 minutes on my machine withJava 1.8
. UsingstringBuilder.append("")
takes less than a second for the same query.So the difference is huge. Inside a loop
StringBuilder
is much faster.Can I point out that if you're going to iterate over a collection and use StringBuilder, you may want to check out Apache Commons Lang and StringUtils.join() (in different flavours) ?
Regardless of performance, it'll save you having to create StringBuilders and for loops for what seems like the millionth time.
Version 1 is preferable because it is shorter and the compiler will in fact turn it into version 2 - no performance difference whatsoever.
At the point where you're concatenating in a loop - that's usually when the compiler can't substitute
StringBuilder
by itself.For performance reasons, the use of
+=
(String
concatenation) is discouraged. The reason why is: JavaString
is an immutable, every time a new concatenation is done a newString
is created (the new one has a different fingerprint from the older one already in the String pool ). Creating new strings puts pressure on the GC and slows down the program: object creation is expensive.Below code should make it more practical and clear at the same time.
Results for a run are reported below.
Not considering the results for 1 concatenation (JIT was not yet doing its job), even for 10 concatenations the performance penalty is relevant; for thousands of concatenations, the difference is huge.
Lessons learned from this very quick experiment (easily reproducible with the above code): never use the
+=
to concatenate strings together, even in very basic cases where a few concatenations are needed (as said, creating new strings is expensive anyway and puts pressure on the GC).I think we should go with StringBuilder append approach. Reason is
The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects.
With String builder only one object will created[StringBuilder is muttable] and the further string gets appended to it.
Since Java 1.5, simple one line concatenation with "+" and StringBuilder.append() generate exactly the same bytecode.
So for the sake of code readability, use "+".
2 exceptions :