问题描述
请告诉我比较实时情况字符串
, StringBuffer
和 StringBuilder
?
Please tell me a real time situation to compare String
, StringBuffer
, and StringBuilder
?
推荐答案
可变性差异:
字符串
是不可变,如果您尝试更改其值,则会创建另一个对象,而 StringBuffer
和 StringBuilder
可变,以便他们可以更改其值。
String
is immutable, if you try to alter their values, another object gets created, whereas StringBuffer
and StringBuilder
are mutable so they can change their values.
线程安全差异
StringBuffer
之间的区别和 StringBuilder
是 StringBuffer
是线程安全的。因此,当应用程序只需要在单个线程中运行时,最好使用 StringBuilder
。 StringBuilder
比 StringBuffer
更有效。
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 use StringBuilder
. StringBuilder
is more efficient than StringBuffer
.
情况:
- 如果您的字符串不会更改,请使用String类,因为
字符串
对象是不可变的。 - 如果你的字符串可以改变(例如:在构造字符串时有很多逻辑和操作)并且只能从一个字符串访问线程,使用
StringBuilder
就足够了。 - 如果您的字符串可以更改,并且将从多个线程访问,请使用
StringBuffer
因为StringBuffer
是同步的,所以你有线程安全。
- 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
StringBuffer
becauseStringBuffer
is synchronous so you have thread-safety.
这篇关于String,StringBuffer和StringBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!