String, StringBuffer, and StringBuilder in Java, and stringbuffer in java
No language can be used to process strings. In Java, the String, StringBuffer, and StringBuilder classes are used to process strings. What are the differences between the three statements?
Both of them implement the CharSequence interface. But the implementation process is different.
In fact, their usage is very simple. Here we will look at the usage of StringBuilder.
Public class TestStringBuffer {public static void main (String args []) {StringBuffer str = new StringBuffer ("liuweivan2015"); str. append (0101); // append () method is used to append content to the end of the current string, similar to the string connection // str. deleteCharAt (4); // The deleteCharAt () method is used to delete characters at a specified position and form a new string/str. delete (); // delete () method deletes multiple characters at a time // str. insert (5, "abc"); // insert () is used to insert a string at a specified position // str. setCharAt (8, "e"); // The setCharAt () method is used to modify the character System at the specified position. out. println (str );}}The specific results can be run one by one.
Running Efficiency of String and StringBuffer: Add yuandankuaile 10000 times with String and StringBuffer respectively.
Public class TestSpeed {public static void main (String [] args) {String fragment = "yuandankuaile"; int times = 10000; // use 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"); // use 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 ");}}Result:
Efficiency is obvious.
StringBuffer and StringBuilderThe functions are basically the same and the methods are similar. However, the StringBuffer method is multi-threaded and secure. The StringBuilder method is not multi-threaded and is more efficient.
Summary:
Operate a small amount of data using String;
Use StringBuilder to operate a large amount of data in a single thread;
Use StringBuffer for multi-threaded operations on a large amount of data.