Java String, StringBuilder, StringBuffer
Posted rysz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java String, StringBuilder, StringBuffer相关的知识,希望对你有一定的参考价值。
整理自stackoverflow:
Mutability Difference:
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.
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 use StringBuilder
. 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
StringBuffer
becauseStringBuffer
is synchronous so you have thread-safety.
Also, using String for logic operations is rather slow, and is not advised at all, since the JVM converts the String to a StringBuffer in the bytecode. A lot of overhead is wasted converting from String to StringBuffer and then back to String again.
- You use
String
when an immutable structure is appropriate; obtaining a new character sequence from aString
may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated). - You use
StringBuilder
when you need to create a mutable character sequence, usually to concatenate several character sequences together. - You use
StringBuffer
in the same circumstances you would useStringBuilder
, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).
如果要操作少量的数据,用String ;单线程操作大量数据,用StringBuilder ;多线程操作大量数据,用StringBuffer。
不要使用String类的"+"来进行频繁的拼接,因为那样的性能极差的,应该使用StringBuffer或StringBuilder类
为了获得更好的性能,在构造 StringBuffer 或 StringBuilder 时应尽可能指定它们的容量。当然,如果你操作的字符串长度(length)不超过 16 个字符就不用了,当不指定容量(capacity)时默认构造一个容量为16的对象。不指定容量会显著降低性能。
StringBuilder一般使用在方法内部来完成类似"+"功能,因为是线程不安全的,所以用完以后可以丢弃。StringBuffer主要用在全局变量中。
相同情况下使用 StringBuilder 相比使用 StringBuffer 仅能获得 10%~15% 左右的性能提升,但却要冒多线程不安全的风险。而在现实的模块化编程中,负责某一模块的程序员不一定能清晰地判断该模块是否会放入多线程的环境中运行,因此:除非确定系统的瓶颈是在 StringBuffer 上,并且确定你的模块不会运行在多线程模式下,才可以采用StringBuilder;否则还是用StringBuffer。
以上是关于Java String, StringBuilder, StringBuffer的主要内容,如果未能解决你的问题,请参考以下文章