In the Java language, the classes used to handle strings are commonly used in 3: string, StringBuffer, StringBuilder.
Their similarities and differences:
1) are final classes, are not allowed to be inherited;
2) String length is immutable, stringbuffer, StringBuilder length is variable;
3) StringBuffer is thread-safe and StringBuilder is not thread-safe. This means that many of the methods in the StringBuffer class use the Synchronized keyword modifier, which allows multithreading to manipulate strings.
Three classes most of the time performance: StringBuilder "StringBuffer" String.
4) The use of StringBuffer and StringBuilder methods is basically the same
Test the performance using the following code:
1 Public classTeststringclass {2 3 Private Final intLOOPS = 200000;4 Private FinalString constant_string = "Java-string";5 6 Public Static voidMain (string[] args) {7 8 NewTeststringclass (). teststring ();9 NewTeststringclass (). Teststringbuffer ();Ten NewTeststringclass (). Teststringbullder (); One } A - Public voidteststring () { -String string = ""; the LongCurrentTime =System.currenttimemillis (); - for(inti = 0; i < LOOPS; i++) { -string + =constant_string; - } + LongEndTime =System.currenttimemillis (); -System.out.println ("String:" + (EndTime-currenttime)); + } A at Public voidTeststringbuffer () { -StringBuffer StringBuffer =NewStringBuffer (); - LongCurrentTime =System.currenttimemillis (); - for(inti = 0; i < LOOPS; i++) { - stringbuffer.append (constant_string); - } in LongEndTime =System.currenttimemillis (); -System.out.println ("StringBuffer:" + (EndTime-currenttime)); to } + - Public voidTeststringbullder () { theStringBuilder StringBuilder =NewStringBuilder (); * LongCurrentTime =System.currenttimemillis (); $ for(inti = 0; i < LOOPS; i++) {Panax Notoginseng stringbuilder.append (constant_string); - } the LongEndTime =System.currenttimemillis (); +System.out.println ("Stringbullder:" + (EndTime-currenttime)); A } the}
Results:
string:149549
Stringbuffer:9
Stringbullder:7
The difference is obvious. String has a bad performance.
However, if you use string constants in the compile phase, the performance of string will be very fast.
Summarize:
1. Using string constants at compile time, use string. For example: String haha = "I" + "AM" + "Java";
2. Without regard to thread safety, the append efficiency of the StringBuilder object is higher than the StringBuffer object's append efficiency higher than the "+" connection operation of the string object.
3. In the case of multi-threaded synchronization, it is recommended to use StringBuffer.
Java's String,stringbuffer,stringbuilder class