First, speed, or execution speed. Second, thread safety
Original link: [www.cnblogs.com/su-feng/p/6…] :
There are two main differences between the three classes: speed and thread-safety
1. First of all, running speed, or execution speed
The speed is: StringBuilder > StringBuffer > String
String is the slowest.
String is a String constant, while StringBuilder and StringBuffer are String variables, meaning that a String object cannot be changed once created, whereas the latter two objects are variables and can be changed. Take the following code for example:
1 String str="abc";
2 System.out.println(str);
3 str=str+"de";
4 System.out.println(str);
Copy the code
If you run this code, you’ll see that it prints “ABC” and then “abcde” as if STR has been changed. This is just an illusion. The JVM does this by creating a String STR and assigning “ABC” to STR. In fact, the JVM creates a new object named STR, and then adds the value of the original STR and “de” to the new STR. The original STR is collected by the JVM’s garbage collection (GC), so STR is not actually changed. Once a String is created, it cannot be changed. So, Java operations on strings are really a process of constantly creating new objects and reclaiming old ones, so execution is slow.
StringBuilder and StringBuffer objects are variables, and manipulating variables directly changes the object without creating or recycling it, so it’s much faster than String.
In addition, sometimes we will assign strings like this
1 String str="abc"+"de";
2 StringBuilder stringBuilder=new StringBuilder().append("abc").append("de");
3 System.out.println(str);
4 System.out.println(stringBuilder.toString());
Copy the code
The output is also “abcde” and “abcde”, but String is much faster than StringBuilder because of the sum in line 1
String STR = “abcde”.
It’s exactly the same thing, so it’s going to be fast, and if I write it like this
1 String str1="abc";
2 String str2="de";
3 String str=str1+str2;
Copy the code
The JVM is constantly creating and recycling objects to do this, as described above. It’s going to be slow.
2. Thread safety
In thread-safety, StringBuilder is thread-unsafe, whereas StringBuffer is thread-safe
If a StringBuffer object is used by multiple threads in the StringBuffer, many of the methods in StringBuffer can carry the synchronized keyword, which is thread-safe, but the methods in StringBuilder do not. Therefore, thread safety is not guaranteed, and some wrong operations may occur. So if the operation is multithreaded, use StringBuffer, but in single-threaded cases, the faster StringBuilder is recommended.
3. To sum up
String: Applies to a small number of String operations
StringBuilder: This is suitable for large operations in the character buffer under a single thread
StringBuffer: Applies to multiple threads where a large number of operations are performed in the character buffer