欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

string stringbuffer stringbuilder区别

程序员文章站 2022-07-14 11:49:51
...
string 是不可变类,内部数据结构为final char数组,字符串拼接时会创建新的string对象,从而导致性能问题,性能会差别2000倍左右(基准stringbuilder执行时间)
stringbuffer是可变类,并且是线程安全的,synchronized方法构成,内部数据结构为char数组,其字符串拼接是基于char数组的拼接,期间并不创建新对象(对比string),但由于synchronized标识方法签名,导致一定效率下降,其性能为2倍左右(基准stringbuilder执行时间)
stringbuilder同样是可变类,内部数据结构跟stringbuffer相同,不同点是没有synchronized方法签名,其设计思路与hashtable hashmap类似,为了对线程安全不敏感的地方提供了一种提升效率的可能(亦或者单线程调用本身就是线程安全的),其性能相对为最高

测试代码 借鉴于:http://www.cnblogs.com/Fskjb/archive/2010/04/19/1715176.html

package daily.y2016.m3.d07.a1;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
* @author: chengtai.he
* @created:2009-12-9 上午09:59:57
*/
public class StringBuilderTester {
private static final String base = " base string. ";
private static final int count = 2000000;

public static void stringTest() {
long begin, end;
begin = System.currentTimeMillis();
String test = new String(base);
for (int i = 0; i < count / 100; i++) {
test = test + " add ";
}
end = System.currentTimeMillis();
System.out.println((end - begin) + " millis has elapsed when used String. ");
}

public static void stringBufferTest() {
long begin, end;
begin = System.currentTimeMillis();
StringBuffer test = new StringBuffer(base);
for (int i = 0; i < count; i++) {
test = test.append(" add ");
}
end = System.currentTimeMillis();
System.out.println((end - begin) + " millis has elapsed when used StringBuffer. ");
}

public static void stringBuilderTest() {
long begin, end;
begin = System.currentTimeMillis();
StringBuilder test = new StringBuilder(base);
for (int i = 0; i < count; i++) {
test = test.append(" add ");
}
end = System.currentTimeMillis();
System.out.println((end - begin) + " millis has elapsed when used StringBuilder. ");
}

public static String appendItemsToStringBuiler(List list) {
StringBuilder b = new StringBuilder();

for (Iterator i = list.iterator(); i.hasNext();) {
b.append(i.next()).append(" ");
}

return b.toString();
}

public static void addToStringBuilder() {
List list = new ArrayList();
list.add(" I ");
list.add(" play ");
list.add(" Bourgeois ");
list.add(" guitars ");
list.add(" and ");
list.add(" Huber ");
list.add(" banjos ");

System.out.println(StringBuilderTester.appendItemsToStirngBuffer(list));
}

public static String appendItemsToStirngBuffer(List list) {
StringBuffer b = new StringBuffer();

for (Iterator i = list.iterator(); i.hasNext();) {
b.append(i.next()).append(" ");
}

return b.toString();
}

public static void addToStringBuffer() {
List list = new ArrayList();
list.add(" I ");
list.add(" play ");
list.add(" Bourgeois ");
list.add(" guitars ");
list.add(" and ");
list.add(" Huber ");
list.add(" banjos ");

System.out.println(StringBuilderTester.appendItemsToStirngBuffer(list));
}

public static void main(String[] args) {
stringTest();
stringBufferTest();
stringBuilderTest();
addToStringBuffer();
addToStringBuilder();
}
}