请告诉我一个实时情况比较字符串,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/
其他回答
You use String when an immutable structure is appropriate; obtaining a new character sequence from a String 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 use StringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).
这里有一个例子。
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.
注意,如果您使用的是Java 5或更新版本,您应该使用StringBuilder而不是StringBuffer。来自API文档:
从JDK 5发行版开始,这个类已经被一个为单个线程使用而设计的等效类StringBuilder所补充。通常应该优先使用StringBuilder类,因为它支持所有相同的操作,但速度更快,因为它不执行同步。
在实践中,您几乎永远不会同时从多个线程中使用它,因此StringBuffer所做的同步几乎总是不必要的开销。
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 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流和数组操作
- Java Regex捕获组
- 如何在Python中按字母顺序排序字符串中的字母
- Openssl不被视为内部或外部命令
- 如何添加自定义方法到Spring Data JPA
- 如何在Ubuntu中设置Java环境路径
- 无法执行dex:在Eclipse中超过GC开销限制
- 有人能解释一下JPA和Hibernate中的mappedBy吗?
- 是什么导致JNI调用变慢?
- Java中的&和&&有什么区别?
- 使用Java的Collections.singletonList()?
- python: SyntaxError: EOL扫描字符串文字
- PHP子字符串提取。获取第一个'/'之前的字符串或整个字符串
- Maven使用多个src目录编译
- 导入时无法解析符号