Brief analysis of String, StringBuffer and StringBuilder

Brief analysis of String, StringBuffer and StringBuilder

  • Briefly describe the String
    String class, that is, the string class, has immutability, which is embodied in: every time the String object is changed, a temporary new String object will be generated, and then the pointer will point to the new object; for example, the String object connection operation.
    System.out.println("abc");
     String cde = "cde";
     String abcde = "abc" + cde;
     System.out.println(abcde );

The concatenation operation of String objects uses the StringBuilder (or StringBuffer) class and its append initialization method internally. According to the JAVA bytecode, the actual steps of the above code are as follows:
1. Generate a StringBuilder temporary variable and initialize it with the string "abc";
2. Use the append method of the StringBuilder class to connect the string "abc";
3. The temporary StringBuilder variable calls toString () method returns.

String abcde = new StringBuilder("abc").append("cde").toString();

Because each generation of objects has a certain impact on the system performance, it is recommended not to use the String class for strings that change frequently, and the efficiency will be relatively low.

  • StringBuilder vs StringBuffer
    StringBuilder is volatile, but not thread-safe, suitable for a single thread; the most basic methods in the StringBuilder class are the insert(), append() and toString() methods.
    StringBuffer is volatile and thread-safe. Because the operations that change in StringBuffer use synchronized synchronization locks 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, which can be accessed by multiple threads, and the string can be modified by calling the insert() and append() methods.

  • Speed ​​comparison**
    StringBuffer > StringBuilder >String
    StringBuilder has better performance as explained in the first example in the text;
    see the source code for the performance comparison of StringBuilder and StringBuffer:

StringBuilder's append method:

 @Override
    public StringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }

The execution of the append method in StringBuffer needs to meet certain conditions, that is, the Buffer can be modified only after the Buffer synchronized lock is successful. Locking will bring performance loss.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325925730&siteId=291194637