Deeply analyze the difference between StringBuffer and StringBuilder

String and StringBuilder are often used in projects. String can be spliced with "+" and StringBuilder can be spliced with append. I still don't understand why to use StringBuilder since string can be used. Although we habitually use StringBuilder to splice query statements when doing database query, we still don't know the reason. When watching the video today, I saw StringBuffer again. I felt that the usage was similar, so I specially checked the differences between these things. It can be summarized as follows: 1 Comparison in execution speed: StringBuilder > StringBuffer 2 StringBuffer and StringBuilder are string variables and changeable objects. Whenever we use them to operate on a string, we actually operate on an object. Unlike string, we create some objects for operation, so the speed is fast. 3. StringBuilder: thread unsafe StringBuffer: thread safe. When we are used by multiple threads in the string buffer, the JVM cannot guarantee that the operation of StringBuilder is safe. Although it is the fastest, it can ensure that the StringBuffer can operate correctly. Of course, in most cases, we operate in a single thread, so in most cases, it is recommended to use StringBuilder instead of StringBuffer, which is the reason for speed.

Summary of the use of the three: 1 If you want to manipulate a small amount of data, use string 2 Single thread operation string buffer operates a large amount of data StringBuilder 3 Multithreaded operation string buffer to operate a large amount of data

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>