The String type is an object in Java. It is an immutable object. Whenever you change the String, you need to generate a new String object, and then point the pointer to a new object. If you are in a loop, it will continue to change. An object must continuously generate new objects, and if there are too many objects, Java's garbage collection mechanism will start to work, so the efficiency will be very low. It is recommended not to use the String type where the String object is constantly changed.
StringBuffer string variable (thread safety)
StringBuffer is a mutable object, that is, each operation is to operate on the object itself, without generating new objects, so the efficiency will definitely be greatly improved. In most cases, the efficiency of StringBuffer is better than that of String type. high.
StringBuilder string variable (not thread safe)
Stringbuilder is a variable character sequence like StringBuffer. It provides API compatible with StringBuffer, but synchronization is not guaranteed. It is used when the string buffer is used by a single thread. It is better to use StringBuilder in the case of a single machine and not a multi-thread. The efficiency, because Stringbuilder does not deal with synchronization (Synchronized) issues. StringBuffer will deal with synchronization issues. If StringBuilder will be operated in multiple threads, StringBuffer must be used instead to let the object manage synchronization issues by itself.
important point:
Specifying its capacity when using StringBuffer will be about 40% to 50% faster than not specifying its capacity, and even faster than StringBuilder without specifying its capacity. Therefore, it is best to specify its capacity when using it. This is a good programming habit and greatly improves performance.