[quote]Mutability Difference:
String is immutable, if you try to alter their values, another object gets created, whereasStringBuffer and StringBuilder are mutable so they can change their values.
Thread-Safety Difference:
The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to useStringBuilder. StringBuilder is more efficient than StringBuffer.
Situations:
* If your string is not going to change use a String class because a String object is immutable.
* If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.
* If your string can change, and will be accessed from multiple threads, use a StringBufferbecause StringBuffer is synchronous so you have thread-safety.
[/quote]
[b]对于可变性而言:[/b]
意思是说String是不可变的,如果要改变它们的值,就会创建新的对象。
而StringBuffer和StringBuilder是可变的,所以可以改变它们的值。
[b]对于线程安全而言:[/b]
StringBuffer是线程安全的,当应用程序只能运行在单线程的时候StringBuffer是优于StringBuffer的,当然这样的话StringBuilder的效率是高于StringBuffer的。
[b]应用场景:[/b]
如果string不会发生改变使用String,因为String是不可变的。
如果string发生改变,如果只能应用于单线程,那么StringBuilder就足够使用了。
如果string发生改变,应用于多线程场景,就需要考虑线程安全的因素,所以需要使用StringBuffer。因为StringBuffer是同步的。
参考资料:
http://stackoverflow.com/questions/2971315/string-stringbuffer-and-stringbuilder
http://kaioa.com/node/59
String is immutable, if you try to alter their values, another object gets created, whereasStringBuffer and StringBuilder are mutable so they can change their values.
Thread-Safety Difference:
The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to useStringBuilder. StringBuilder is more efficient than StringBuffer.
Situations:
* If your string is not going to change use a String class because a String object is immutable.
* If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.
* If your string can change, and will be accessed from multiple threads, use a StringBufferbecause StringBuffer is synchronous so you have thread-safety.
[/quote]
[b]对于可变性而言:[/b]
意思是说String是不可变的,如果要改变它们的值,就会创建新的对象。
而StringBuffer和StringBuilder是可变的,所以可以改变它们的值。
[b]对于线程安全而言:[/b]
StringBuffer是线程安全的,当应用程序只能运行在单线程的时候StringBuffer是优于StringBuffer的,当然这样的话StringBuilder的效率是高于StringBuffer的。
[b]应用场景:[/b]
如果string不会发生改变使用String,因为String是不可变的。
如果string发生改变,如果只能应用于单线程,那么StringBuilder就足够使用了。
如果string发生改变,应用于多线程场景,就需要考虑线程安全的因素,所以需要使用StringBuffer。因为StringBuffer是同步的。
参考资料:
http://stackoverflow.com/questions/2971315/string-stringbuffer-and-stringbuilder
http://kaioa.com/node/59