31. What is the difference between String, StringBuffer and StringBuilder in java?

String String constant

  1. 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.

String

StringBuffer string variable (thread safety)

  1. 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.

StringBuffer

StringBuilder string variable (not thread safe)

  1. 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.

StringBuilder

important point:

  1. 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.

Guess you like

Origin blog.csdn.net/zhu_fangyuan/article/details/108739935