吧啦吧啦,今天在公司做算法题的时候,不仅就想写下了
String是不可变类,所以任何对String的操作都将引发新的String对象的生成。但是StringBuffer是可变类,任何对StringBuffer所指代的字符串改变都不会产生新的对象。
新引入的StingBuilder类不是线程安全,但其在单线程中的性能比StringBuffer高。
下面是一点小例子
代码语言:javascript复制import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 从JDK1.5中,有了StringBuilder。
*/
public class DifferenceStringBufferAndStringBuilder {
private static final String base = "String";
private static final int count = 3000000;
public static void main(String[] args) {
stringTest();
stringBufferTest();
stringBuilderTest();
addToStringBuilder();
addToStringBuffer();
}
/**
* string执行性能测试
*/
public static void stringTest() {
long begin, end;
begin = System.currentTimeMillis();
String test = new String(base);
// 在这里为什么要缩150,因为其实时间是很长的
for (int i = 0; i < count / 150; i ) {
test = test "add";
}
end = System.currentTimeMillis();
System.out.println((end - begin) "millis has elapsed when used String");
}
/**
* stringBuffer
*/
public static void stringBufferTest() {
long begin, end;
begin = System.currentTimeMillis();
StringBuffer stringBuffer = new StringBuffer(base);
for (int i = 0; i < count; i ) {
stringBuffer.append("add");
}
end = System.currentTimeMillis();
System.out.println((end - begin) "millis has elapsed when used StringBuffer");
}
/**
* stingBuilder
*/
public static void stringBuilderTest() {
long begin, end;
begin = System.currentTimeMillis();
StringBuilder stringBuilder = new StringBuilder(base);
for (int i = 0; i < count; i ) {
stringBuilder.append("add");
}
end = System.currentTimeMillis();
System.out.println((end - begin) "mills has elapsed when used StringBuilder");
}
/**
*转换为StringBuilder
*/
public static String appendItemsToStringBuilder(List list){
StringBuilder stringBuilder = new StringBuilder();
for (Iterator i = list.iterator();i.hasNext();){
stringBuilder.append(i.next()).append("");
}
return stringBuilder.toString();
}
public static void addToStringBuilder(){
List list = new ArrayList();
list.add("l");
list.add("y");
list.add("z");
System.out.println(DifferenceStringBufferAndStringBuilder.appendItemsToStringBuilder(list));
}
public static String appendItemsToStringBuffer(List list){
StringBuffer stringBuffer = new StringBuffer();
for (Iterator i = list.iterator();i.hasNext();){
stringBuffer.append(i.next()).append("");
}
return stringBuffer.toString();
}
public static void addToStringBuffer(){
List list = new ArrayList();
list.add("l");
list.add("y");
list.add("z");
System.out.println(DifferenceStringBufferAndStringBuilder.appendItemsToStringBuffer(list));
}
}
最后输出的是
代码语言:javascript复制1127millis has elapsed when used String
86millis has elapsed when used StringBuffer
35mills has elapsed when used StringBuilder
lyz
lyz
所以根据结果来看,采用String对象时,哪怕是次数是其他对象的1/150,执行时间上也比其他对象高很多,而采用StringBuffer对象和采用StringBuilder对象也有明显的差距。所以如果是在单线程下运行,就不必考虑到线程同步的问题,优先采用StringBuilder类,当然,如果是要保证线程安全的话,就要考虑到StringBuffer了。
除了对多线程的支持不一样的话,其实这两个类没啥区别的,上面不就很好的说明了嘛。