改变String字符串的内容,增加或者删除的时候,String都会创建一个新的String对象,导致效率低下,所以引入了StringBuffer,在JDK1.5之后又引入了StringBuilder
StringBuffer 是线程安全的,但同时也比较耗时,因为线程安全,所以都要执行同步synchronized的操作
StringBuilder在单线程下运行速度最快,如果程序只是在单线程下运行,使用StringBuilder效率更高
public static void main(String[] args) throws Exception{
int i = 0;
long start = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for(i = 0; i < 1000000; i++){
sb.append(i);
}
long end1 = System.currentTimeMillis();
System.out.println("StringBuilder cost :"+(end1-start)+"ms");
StringBuffer sb2 = new StringBuffer();
for(i = 0; i < 1000000; i++){
sb2.append(i);
}
long end2 = System.currentTimeMillis();
System.out.println("StringBuffer cost :"+(end2-end1)+"ms");
String sb3 = new String();
for(i = 0; i < 1000000; i++){
sb3 += i;
}
long end3 = System.currentTimeMillis();
System.out.println("String cost :"+(end3-end2)+"ms");
}