1. Comparison of execution speed

StringBuilder>StringBuffer>String

Why is String execution slow?

Strings are called immutable strings in the Java documentation. Modifications to strings do not actually change the sequence of code units in the original String, but create a new String. If a large number of strings need to be modified, a new String needs to be built each time a String is modified Object, it’s time-consuming, it’s space wasting, and you can avoid that by using the StringBuilder class if you want to change the string, you just call the Append method

StringBuilder builder=new StringBuilder(); builder.append(ch); //appends a single character builder.append(str); //appends a stringCopy the code

Call toString whenever you need to build a string

String str=builder.toString();
Copy the code

So why does StringBuilder perform better than StringBuffer?

Because StringBuilder doesn’t take into account multithreading, it’s not safe in multithreading, and StringBuffer is thread-safe in multithreading, so it’s certainly not as fast as StringBuilder

2. Many cases StringBuffer, StringBuilder, the use of the String

1. Operate on less data using String, the compiler can make unchanging strings shared

2. Use StringBuilder for a large amount of data in a single thread

3. StingBuffer is used for the amount of multithreaded data