public class Test {public
static void Main (string[] args) {
StringBuffer strbuffer = new StringBuffer ();
Strbuffer.append ("StringBuffer");
Strbuffer.append ("");
Strbuffer.append ("Test");
System.out.println (Strbuffer.tostring ());
StringBuilder Strbuilder = new StringBuilder ();
Strbuilder.append ("StringBuffer");
Strbuilder.append ("");
Strbuilder.append ("Test");
System.out.println (Strbuilder.tostring ());
}
Using StringBuffer and StringBuilder output is the same, only from the source code, StringBuffer:
Public final class StringBuffer
extends Abstractstringbuilder
implements Java.io.Serializable, charsequence{...
Public synchronized StringBuffer append (String str) {
super.append (str);
return this;
}
......
}
Abstractstringbuilder:
Abstract class Abstractstringbuilder implements Appendable, Charsequence {
...
Public Abstractstringbuilder append (String str) {
if (str = null) str = "NULL";
int len = Str.length ();
if (len = = 0) return to this;
int Newcount = count + len;
if (Newcount > Value.length)
expandcapacity (newcount);
Str.getchars (0, Len, value, count);
Count = Newcount;
return this;
}
......
}
You can see that StringBuffer overrides the parent class method and adds synchronization based on the parent class method, so it consumes a certain amount of performance (StringBuffer many methods are synchronous)
Let's look at StringBuilder:
Public final class StringBuilder
extends Abstractstringbuilder
implements Java.io.Serializable, charsequence{...
Public StringBuilder append (String str) {
super.append (str);
return this;
}
......
}
You can see that StringBuilder does not synchronize the method, so it is much more efficient (StringBuilder no Sync method)
For the following code:
public class Test {public
static void Main (string[] args) {
String str = "Just a";
SYSTEM.OUT.PRINTLN (str + "Test");
}
If you compile with JDK1.6, the result is (compile the Test.class file with the Decompile tool after compiling, and if you are concerned about the inaccurate compilation of the Decompile tool, you can view the result of the test class directly through the JAVAP command):
public class test{public
Test () {} public
static void Main (String args[]) {
string str = "Just a";
System.out.println (New StringBuilder (
string.valueof (str)). Append ("Test"). toString ());
Java bottom through StringBuilder implementation of the "+" symbolic connection string function
Of course, for simple string concatenation:
public class Test {public
static void Main (string[] args) {
string result = ' string ' + ' ' + ' test ';
}
}
The results of the compilation are:
public class test{public
Test () {} public
static void main (string args[]) {
string = ' string Test '; c19/>}
}