请告诉我一个实时情况比较字符串,StringBuffer,和StringBuilder?
当前回答
String和其他两个类的区别在于String是不可变的,而其他两个类是可变的。
但是为什么我们有两个相同目的的类呢?
原因是StringBuffer是线程安全的,而StringBuilder不是。 StringBuilder是StringBuffer Api上的一个新类,它是在JDK5中引入的,如果你工作在单线程环境中,总是推荐使用它,因为它要快得多
有关完整的详细信息,请访问http://www.codingeek.com/java/stringbuilder-and-stringbuffer-a-way-to-create-mutable-strings-in-java/
其他回答
String和其他两个类的区别在于String是不可变的,而其他两个类是可变的。
但是为什么我们有两个相同目的的类呢?
原因是StringBuffer是线程安全的,而StringBuilder不是。 StringBuilder是StringBuffer Api上的一个新类,它是在JDK5中引入的,如果你工作在单线程环境中,总是推荐使用它,因为它要快得多
有关完整的详细信息,请访问http://www.codingeek.com/java/stringbuilder-and-stringbuffer-a-way-to-create-mutable-strings-in-java/
In java, String is immutable. Being immutable we mean that once a String is created, we can not change its value. StringBuffer is mutable. Once a StringBuffer object is created, we just append the content to the value of object instead of creating a new object. StringBuilder is similar to StringBuffer but it is not thread-safe. Methods of StingBuilder are not synchronized but in comparison to other Strings, the Stringbuilder runs fastest. You can learn difference between String, StringBuilder and StringBuffer by implementing them.
就我个人而言,我认为StringBuffer在现实世界中没有任何用处。什么时候我想通过操纵字符序列在多个线程之间进行通信?这听起来一点用都没有,但也许我还没有看到光明:)
注意,如果您使用的是Java 5或更新版本,您应该使用StringBuilder而不是StringBuffer。来自API文档:
从JDK 5发行版开始,这个类已经被一个为单个线程使用而设计的等效类StringBuilder所补充。通常应该优先使用StringBuilder类,因为它支持所有相同的操作,但速度更快,因为它不执行同步。
在实践中,您几乎永远不会同时从多个线程中使用它,因此StringBuffer所做的同步几乎总是不必要的开销。
---------------------------------------------------------------------------------- String StringBuffer StringBuilder ---------------------------------------------------------------------------------- Storage Area | Constant String Pool Heap Heap Modifiable | No (immutable) Yes( mutable ) Yes( mutable ) Thread Safe | Yes Yes No Performance | Fast Very slow Fast ----------------------------------------------------------------------------------
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- Printf与std::字符串?
- 在Jar文件中运行类
- 带参数的可运行?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- 如何在PHP中截断字符串最接近于一定数量的字符?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作