StringBuffer vs StringBuilder
This question already has an answer here:
StringBuffer
has all methods synchronized.
From java doc:
A thread-safe, mutable sequence of characters
Synchronization is a system to synchronize thread access to portion of code so that at most one thread can execute a synchronized block.
If your code is not multithreading or simply if the StringBuffer
you are using is not shared between threads use StringBuilder
. It is faster.
From javadoc of StringBuilder:
A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization . This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case) . Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
Since all of its methods are synchronized, it means that even if you have 100 threads (or more) using and modifying it at the same time, it will perform each operation fully before handling other requests. With a StringBuilder you have no such guarantees.
链接地址: http://www.djcxy.com/p/72342.html