A brief analysis of String, StringBuffer and StringBuilder
Brief description String
The string class, which is a string class, is immutable, in that each time a string object is changed, a temporary new string object is generated, and then the pointer points to a new object; For example, a string object's connection operation.
SYSTEM.OUT.PRINTLN ("abc");
String CDE = "CDE";
String ABCDE = "abc" + CDE;
System.out.println (ABCDE);
The StringBuilder (or StringBuffer) class and its Append initialization method are used internally in a string object's connection (concatenation) operation. Based on the Java bytecode, the actual steps of the preceding code are as follows:
1. Generate StringBuilder temporary variables and initialize them using the string "ABC";
2. Use the Append method of the StringBuilder class to connect the string "abc";
3. The temporary StringBuilder variable calls the ToString () method to return.
String ABCDE = new StringBuilder ("abc"). Append ("CDE"). ToString ();
Because each generation of objects has a certain impact on system performance, it is less efficient to suggest that you do not use string classes for frequently changing strings. StringBuilder vs StringBuffer
StringBuilder is variable, but is not thread-safe, and is suitable for single-threaded, the most basic method in the StringBuilder class is the Insert (), append (), and ToString () methods.
StringBuffer is variable, thread-safe. Because the stringbuffer changes in the operation are used synchronized synchronous lock to ensure thread safety. For example, the Java source code in StringBuffer is as follows:
@Override public
synchronized StringBuffer append (double D) {
tostringcache = null;
Super.append (d);
return this;
}
StringBuffer is like a string buffer, accessible by multiple threads, and can be modified by the insert () and append () method calls. Speed Comparison * *
StringBuffer > StringBuilder >string
The StringBuilder performance is better in the first example of the article;
StringBuilder and StringBuffer Performance comparison See source code:
The Append method of StringBuilder:
@Override public
StringBuilder append (Object obj) {return
append (string.valueof (obj));
}
The execution of the Append method in the
StringBuffer needs to satisfy a certain condition, that is, wait for the buffer synchronized lock to be successful before the buffer can be modified. Adding locks can lead to performance losses.