字节流的博客

StringBuffer 和 StringBuilder 的区别

1. StringBuffer 和 StringBuilder

在 Java 中 String 是字符串常量,通过 String 声明的对象放在内存中是不变的,每次对该变量的拼接、截取等类似操作,都会产生一个新的对象。
而 StringBuilder 和 StringBuffer 都是字符串变量,常用于字符串拼接、截取等操作,该对象会发生相应变化,并不会产生一个新的对象;

StringBuilder 和 StringBuffer 的主要区别是:StringBuffer 是线程安全的,而 StringBuilder 是非线程安全的;

所以,通常来说,StringBuilder 执行速度相对 StringBuffer 要快,但是多线程情况下,应使用 StringBuffer 来保证数据的安全。

JDK 文档介绍 StringBuilder 如下:

A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

StringBuilder 和 StringBuffer 速度测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void main(String[] args) {
int times = 20000000;

{
StringBuilder stringBuilder = new StringBuilder("");
String helloWorld = "Hello World";
Long begin = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
stringBuilder.append(helloWorld);
}
System.out.println("StringBuilder Waste Time: " + (System.currentTimeMillis() - begin));
}
{
StringBuffer stringBuffer = new StringBuffer("");
String helloWorld = "Hello World";
Long begin = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
stringBuffer.append(helloWorld);
}
System.out.println("StringBuffer Waste Time: " + (System.currentTimeMillis() - begin));
}

}

运行结果如下:

1
2
StringBuilder Waste Time: 853
StringBuffer Waste Time: 1273

Thanks! 😊