关于java:StringBuilder和Stringbuffer有什么区别?

what is the difference between StringBuilder and Stringbuffer?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
StringBuilder and StringBuffer in Java

StringBuilder和StringBuffer有什么区别?


StringBuffer中的某些方法是同步的,而StringBuilder不是线程安全的,而且速度更快。

经验法则-除非有用例,否则使用StringBuilder,其中一个StringBuilder被多个线程使用(这是非常罕见的情况)。


取自StringBuffer的javaDoc:

As of release JDK 5, this class has
been supplemented with an equivalent
class designed for use by a single
thread, {@link StringBuilder}. The
StringBuilder class should
generally be used in preference to
this one, as it supports all of the
same operations but it is faster, as
it performs no synchronization.

基本上,StringBuffer可以同时被多个线程使用,因为它是同步的,但这也使得它比一次只能由一个线程使用的StringBuilder慢一些。