Assuming String a and b:
a += b
a = a.concat(b)
Under the hood, are they the same thing?
Here is concat decompiled as reference. I'd like to be able to decompile the +
operator as well to see what that does.
public String concat(String s) {
int i = s.length();
if (i == 0) {
return this;
}
else {
char ac[] = new char[count + i];
getChars(0, count, ac, 0);
s.getChars(0, i, ac, count);
return new String(0, count + i, ac);
}
}
I ran a similar test as @marcio but with the following loop instead:
Just for good measure, I threw in
StringBuilder.append()
as well. Each test was run 10 times, with 100k reps for each run. Here are the results:StringBuilder
wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.a += b
takes about 40000ms (40s) for each run.concat
only requires 10000ms (10s) per run.I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect
a += b
spends much of the time creating new objects ofStringBuilder
and then converting them back toString
.Most answers here are from 2008. It looks that things have changed over the time. My latest benchmarks made with JMH shows that on Java 8
+
is around two times faster thanconcat
.My benchmark:
Results:
For the sake of completeness, I wanted to add that the definition of the '+' operator can be found in the JLS SE8 15.18.1:
About the implementation the JLS says the following:
So judging from the 'a Java compiler may use the StringBuffer class or a similar technique to reduce', different compilers could produce different byte-code.
The + operator can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.
The concat operator can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.
Except this, the code you provided does the same stuff.
Tom is correct in describing exactly what the + operator does. It creates a temporary
StringBuilder
, appends the parts, and finishes withtoString()
.However, all of the answers so far are ignoring the effects of HotSpot runtime optimizations. Specifically, these temporary operations are recognized as a common pattern and are replaced with more efficient machine code at run-time.
@marcio: You've created a micro-benchmark; with modern JVM's this is not a valid way to profile code.
The reason run-time optimization matters is that many of these differences in code -- even including object-creation -- are completely different once HotSpot gets going. The only way to know for sure is profiling your code in situ.
Finally, all of these methods are in fact incredibly fast. This might be a case of premature optimization. If you have code that concatenates strings a lot, the way to get maximum speed probably has nothing to do with which operators you choose and instead the algorithm you're using!