No language can handle strings. Three classes of string, StringBuffer, and StringBuilder are processed in Java. What's the difference between the three of them?
All three of them implemented the Charsequence interface. But the implementation process is different.
in fact, their use of the method is very simple, here to see the use of StringBuilder.
public class Teststringbuffer{public static void Main (String args[]) {stringbuffer str=new stringbuffer ("liuweivan2015" ); Str.append (0101); the//append () method is used to append content to the end of the current string, similar to the string's connection//str.deletecharat (4), and the//deletecharat () method to delete the character at the specified position. And the remaining characters form a new string//str.delete (1,4); the//delete () method deletes multiple characters//str.insert (5, "abc") at once, and//insert () is used to insert the string at the specified position// Str.setcharat (8, "E"); the//setcharat () method is used to modify the character System.out.println (str) at the specified position;}}
specific results can be run one by one to see.
operation Efficiency of string and StringBuffer : Add Yuandankuaile 10,000 times with string and StringBuffer respectively
public class Testspeed {public static void Main (string[] args) { String fragment = "Yuandankuaile"; int times = 10000; Via string long TimeStart1 = System.currenttimemillis (); String str1 = ""; for (int i=0; i<times; i++) { str1 + = fragment; } Long timeEnd1 = System.currenttimemillis (); System.out.println ("String:" + (TIMEEND1-TIMESTART1) + "MS"); by StringBuffer Long timeStart2 = System.currenttimemillis (); StringBuffer str2 = new StringBuffer (); for (int i=0; i<times; i++) { str2.append (fragment); } Long TimeEnd2 = System.currenttimemillis (); System.out.println ("StringBuffer:" + (TIMEEND2-TIMESTART2) + "MS");} }
Results:
efficiency is obvious.
StringBuffer and StringBuilder functions are basically the same, and the methods are similar. But the StringBuffer method is multithreaded, secure, and the StringBuilder method is not multithreaded security, its efficiency is relatively fast.
Summary:
Manipulate small amounts of data using String;
Single-threaded operation of large amounts of data using StringBuilder;
Multithreading operations large amounts of data using StringBuffer.
String, StringBuffer, and StringBuilder in Java