Dig into the differences between StringBuffer and StringBuilder

  • 2020-04-01 02:11:24
  • OfStack

String and StringBuilder are often used in projects. String can be used to concatenate strings with "+", and StringBuilder can be used to concatenate strings with append. I have never understood why I need to use StringBuilder since I can use String. Although it is customary to use StringBuilder to splicing query statements when doing database queries, we still don't know why. When I watched the video today, I saw StringBuffer again, and it felt like it was used similarly, so I looked up the difference between these things.
The summary is as follows:
1. Comparison of execution speed: StringBuilder >   StringBuffer   

2.StringBuffer and StringBuilder, they are String variables, are mutable objects, and whenever we do something with them on a String, we're actually doing it on an object, not creating some objects like String, so it's faster.

3.StringBuilder: threads are not safe
StringBuffer: thread-safe

The JVM cannot guarantee that the StringBuilder's operation is safe when it is used by multiple threads in string buffering, and while it is the fastest, it can guarantee that the StringBuffer can operate correctly. Of course, most of the time we're doing this in a single thread, so most of the time it's recommended to use StringBuilder instead of StringBuffer, just for speed.

Summary of the use of the three:
1. String if you want to manipulate a small amount of data
2. Single thread operation string buffer to operate a large number of data   The StringBuilder
3. Multithreaded operation string buffer to operate a large number of data   StringBuffer


Related articles: