Wha's special in using StringBuilder insted of StringBuffer

Possible Duplicate:
StringBuilder and StringBuffer in Java

I would like to know the difference between the StringBuilder and StringBuffer. In StringBuffer it automatically allocates 16 character. When we add a string "hello" its capacity is increased to 21. Could any one clarify my doubts?


Have you looked at the Javadocs?

From http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html:

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.


The main difference is , StringBuffer is thread safe (all of its methods are synchronized),but StringBuilder is not. But StringBuilder is faster than the StringBuffer.Use StringBuilder if you don't need thread-safety.


StringBuffer is thread-safe (ie, its methods are synchronised). However, this isn't needed by every application and it makes the code slower than it would otherwise be. StringBuilder is essentially StringBuffer without the synchronization, and hence a bit faster.

链接地址: http://www.djcxy.com/p/72344.html

上一篇: 为什么StringBuilder访问似乎是同步的?

下一篇: Wha特别使用StringBuilder内嵌的StringBuffer