When learning the three classes of string, StringBuilder, StringBuffer, see the following questions on GitHub: 1. What is the best scenario for a member variable, local variable , 2. How efficient are they, and why 3. There are no special circumstances 4. Compiler optimization for them
Here are some questions to try to answer
Answer 1:
String is an immutable string, and any concatenation or modification is a new string object returned, and the original object has not changed; StringBuilder and StringBuffer are mutable strings, and modification of the operation changes the original object. The difference between StringBuilder and StringBuffer is that StringBuffer is thread-safe, and most of his APIs are decorated with the synchronized keyword. So the use scenario for these three classes is summarized as follows
1 Modify the less operation of the scene can be used string;
2 A single thread case string requires a large number of operations suitable for the use of StringBuilder;
3 multithreading operation in the case of a large number of operation strings suitable for using StringBuffer. Answer 2:
String modification, stitching, and so on, because of the need to reapply new objects so the speed is generally slower than StringBuilder and StringBuffer. The StringBuffer API uses synchronized modification, and generally speeds slower than StringBuilder. Answer 3:
Answer the question with an example
String s = "a" + "B" + "C" + "D";
StringBuilder sb = new StringBuilder ("a"). Append ("B"). Append ("C"). Append ("D");
Answer 2 indicates that the StringBuilder speed is faster than string, and the execution efficiency of these two statements is as follows:
public void Testspeed () {
Long T1 = System.nanotime ();
String s = "a" + "B" + "C" + "D";
Long t2 = System.nanotime ();
System.out.println ("String is time consuming:" + (T2-T1));
long t3 = System.nanotime ();
StringBuilder sb = new StringBuilder ("a"). Append ("B"). Append ("C"). Append ("D");
long T4 = System.nanotime ();
System.out.println ("StringBuilder time is:" + (T4-T3));
}
The results of the execution are:
String time consuming: 3611
StringBuilder time consuming: 13617
Answer 4:
In answer 3, it was pointed out that string efficiency could be higher than StringBuilder, which was the result of the JVM's optimization. In theory, string s = "a" + "B" + "C" + "D"; This statement produces 4 objects that are actually optimized for the JVM to string s = "ABCD", so it is highly efficient.