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);
}
}
Best Answer
No, not quite.
Firstly, there's a slight difference in semantics. If
a
isnull
, thena.concat(b)
throws aNullPointerException
buta+=b
will treat the original value ofa
as if it werenull
. Furthermore, theconcat()
method only acceptsString
values while the+
operator will silently convert the argument to a String (using thetoString()
method for objects). So theconcat()
method is more strict in what it accepts.To look under the hood, write a simple class with
a += b;
Now disassemble with
javap -c
(included in the Sun JDK). You should see a listing including:So,
a += b
is the equivalent ofThe
concat
method should be faster. However, with more strings theStringBuilder
method wins, at least in terms of performance.The source code of
String
andStringBuilder
(and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the finalString
. In practice memory allocation is surprisingly fast.Update: As Pawel Adamski notes, performance has changed in more recent HotSpot.
javac
still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. SummingSystem.identityHashCode
(notString.hashCode
) shows theStringBuffer
code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.