StringBuffer和StringBuilder之间的主要区别是什么?在决定其中任何一项时是否存在性能问题?
当前回答
一个简单的程序说明了StringBuffer和StringBuilder之间的区别:
/**
* Run this program a couple of times. We see that the StringBuilder does not
* give us reliable results because its methods are not thread-safe as compared
* to StringBuffer.
*
* For example, the single append in StringBuffer is thread-safe, i.e.
* only one thread can call append() at any time and would finish writing
* back to memory one at a time. In contrast, the append() in the StringBuilder
* class can be called concurrently by many threads, so the final size of the
* StringBuilder is sometimes less than expected.
*
*/
public class StringBufferVSStringBuilder {
public static void main(String[] args) throws InterruptedException {
int n = 10;
//*************************String Builder Test*******************************//
StringBuilder sb = new StringBuilder();
StringBuilderTest[] builderThreads = new StringBuilderTest[n];
for (int i = 0; i < n; i++) {
builderThreads[i] = new StringBuilderTest(sb);
}
for (int i = 0; i < n; i++) {
builderThreads[i].start();
}
for (int i = 0; i < n; i++) {
builderThreads[i].join();
}
System.out.println("StringBuilderTest: Expected result is 1000; got " + sb.length());
//*************************String Buffer Test*******************************//
StringBuffer sb2 = new StringBuffer();
StringBufferTest[] bufferThreads = new StringBufferTest[n];
for (int i = 0; i < n; i++) {
bufferThreads[i] = new StringBufferTest(sb2);
}
for (int i = 0; i < n; i++) {
bufferThreads[i].start();
}
for (int i = 0; i < n; i++) {
bufferThreads[i].join();
}
System.out.println("StringBufferTest: Expected result is 1000; got " + sb2.length());
}
}
// Every run would attempt to append 100 "A"s to the StringBuilder.
class StringBuilderTest extends Thread {
StringBuilder sb;
public StringBuilderTest (StringBuilder sb) {
this.sb = sb;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
sb.append("A");
}
}
}
//Every run would attempt to append 100 "A"s to the StringBuffer.
class StringBufferTest extends Thread {
StringBuffer sb2;
public StringBufferTest (StringBuffer sb2) {
this.sb2 = sb2;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
sb2.append("A");
}
}
}
其他回答
主要区别在于StringBuffer是同步的,而StringBuilder不是同步的。如果您需要使用多个线程,那么建议使用StringBuffer。但是,根据执行速度,StringBuilder比StringBuffer更快,因为它没有同步。
在单线程中,由于JVM的优化,StringBuffer不会比StringBuilder慢很多。在多线程中,不能安全地使用StringBuilder。
这是我的测试(不是基准测试,只是测试):
public static void main(String[] args) {
String withString ="";
long t0 = System.currentTimeMillis();
for (int i = 0 ; i < 100000; i++){
withString+="some string";
}
System.out.println("strings:" + (System.currentTimeMillis() - t0));
t0 = System.currentTimeMillis();
StringBuffer buf = new StringBuffer();
for (int i = 0 ; i < 100000; i++){
buf.append("some string");
}
System.out.println("Buffers : "+(System.currentTimeMillis() - t0));
t0 = System.currentTimeMillis();
StringBuilder building = new StringBuilder();
for (int i = 0 ; i < 100000; i++){
building.append("some string");
}
System.out.println("Builder : "+(System.currentTimeMillis() - t0));
}
结果:字符串:319740缓冲区:23建设者:7!
因此,构建器比缓冲区更快,比字符串串联更快。现在让我们为多个线程使用Executor:
public class StringsPerf {
public static void main(String[] args) {
ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
//With Buffer
StringBuffer buffer = new StringBuffer();
for (int i = 0 ; i < 10; i++){
executorService.execute(new AppendableRunnable(buffer));
}
shutdownAndAwaitTermination(executorService);
System.out.println(" Thread Buffer : "+ AppendableRunnable.time);
//With Builder
AppendableRunnable.time = 0;
executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < 10; i++){
executorService.execute(new AppendableRunnable(builder));
}
shutdownAndAwaitTermination(executorService);
System.out.println(" Thread Builder: "+ AppendableRunnable.time);
}
static void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // code reduced from Official Javadoc for Executors
try {
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (Exception e) {}
}
}
class AppendableRunnable<T extends Appendable> implements Runnable {
static long time = 0;
T appendable;
public AppendableRunnable(T appendable){
this.appendable = appendable;
}
@Override
public void run(){
long t0 = System.currentTimeMillis();
for (int j = 0 ; j < 10000 ; j++){
try {
appendable.append("some string");
} catch (IOException e) {}
}
time+=(System.currentTimeMillis() - t0);
}
}
现在StringBuffers需要157毫秒才能完成100000次追加。这不是同一个测试,但与之前的37毫秒相比,您可以放心地假设,使用多线程时,StringBuffers追加的速度较慢。原因是JIT/hotspot/compiler/something在检测到不需要检查锁时会进行优化。
但是对于StringBuilder,您有java.lang.ArrayIndexOutOfBoundsException,因为并发线程试图在不应该添加的地方添加一些内容。
结论是,您不必追逐StringBuffers。如果您有线程,在尝试获得几纳秒之前,请考虑它们正在做什么。
javadoc解释了区别:
此类提供与StringBuffer兼容的API,但不保证同步。该类被设计为在单个线程使用字符串缓冲区的地方(通常情况下)作为StringBuffer的替代品。在可能的情况下,建议优先使用该类而不是StringBuffer,因为在大多数实现中,它会更快。
StringBuilder不是线程安全的。字符串缓冲区是。更多信息请点击此处。
编辑:至于性能,在热点启动后,StringBuilder是赢家。然而,对于较小的迭代,性能差异可以忽略不计。
StringBuilder和StringBuffer之间没有基本区别,它们之间只有一些区别。在StringBuffer中,方法是同步的。这意味着一次只能有一个线程对它们进行操作。如果有多个线程,那么第二个线程将不得不等待第一个线程完成,第三个线程将必须等待第一个和第二个完成,依此类推。这使得进程非常缓慢,因此StringBuffer的性能很低。
另一方面,StringBuilder不同步。这意味着多个线程可以同时对同一StringBuilder对象进行操作。这使得过程非常快,因此StringBuilder的性能很高。
推荐文章
- 使用Java重命名文件
- URL从Java中的类路径加载资源
- .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
- Hibernate中不同的保存方法之间有什么区别?
- Java 8流和数组操作
- Java Regex捕获组
- Openssl不被视为内部或外部命令
- 如何添加自定义方法到Spring Data JPA
- 如何在Ubuntu中设置Java环境路径
- 无法执行dex:在Eclipse中超过GC开销限制
- 有人能解释一下JPA和Hibernate中的mappedBy吗?
- 是什么导致JNI调用变慢?
- Java中的&和&&有什么区别?
- 使用Java的Collections.singletonList()?
- Maven使用多个src目录编译