String and StringBuilder are often used in projects. String can be spliced with "+", and StringBuilder can be spliced with append. I have never understood why I should use StringBuilder since I can use String. Although I habitually use StringBuilder to splice query statements when doing database queries, I still don’t know the reason. When I was watching the video today, I saw StringBuffer again, and I felt that the usage was similar, so I checked the differences between these things.
It is summarized as follows:
1. Comparison in terms of execution speed: StringBuilder > StringBuffer
2. StringBuffer and StringBuilder, they are string variables and changeable objects. Whenever we use them to operate on strings, we are actually operating on an object. It is not like creating some objects to operate like String. So the speed is fast.
3.StringBuilder: thread-unsafe
StringBuffer: thread-safe
When our string buffer is used by multiple threads, the JVM cannot guarantee that the operation of StringBuilder is safe. Although it is the fastest, it can guarantee that StringBuffer can operate correctly. Of course, in most cases we perform operations in a single thread, so in most cases it is recommended to use StringBuilder instead of StringBuffer for reasons of speed.
Summary of the use of the three:
1. If you want to operate a small amount of data, use String
2. Single-threaded operation of string buffer to operate a large amount of data StringBuilder
3. Multi-threaded operation of string buffer to operate a large amount of data StringBuffer