1.速度方面
public static void main(String args[]){
String str="abc";
long time1=System.currentTimeMillis();
for(int i=0;i<100000;i++){
str=str+"abc";
}
long time2=System.currentTimeMillis();
System.out.println("String:"+(time2-time1));
StringBuffer stringBuffer =new StringBuffer("abc");
time1=System.currentTimeMillis();
for(int i=0;i<100000000;i++){
stringBuffer.append("abc");
}
time2=System.currentTimeMillis();
System.out.println("StringBuffer:"+(time2-time1));
StringBuilder stringBuilder=new StringBuilder("abc");
time1=System.currentTimeMillis();
for(int i=0;i<100000000;i++){
stringBuilder.append("abc");
}
time2=System.currentTimeMillis();
System.out.println("StringBuilder:"+(time2-time1));
}
结果
String:9427
StringBuffer:1653
StringBuilder:1486
由此可见StringBuilder > StringBuffer > String
2.线程安全方面
public static String string="a";
public static StringBuffer stringbuffer=new StringBuffer("a");
public static StringBuilder stringbuilder=new StringBuilder("a");
public static void main(String args[]){
ExecutorService exe = Executors.newFixedThreadPool(10);
for (int i=0;i<100000;i++) {
String word="-";
exe.execute(new Runnable() {
public void run() {
string+=word+"";
stringbuffer.append(word);
stringbuilder.append(word);
}
});
}
exe.shutdown();
while (!exe.isTerminated()) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("String:"+string.length());
System.out.println("stringbuffer:"+stringbuffer.length());
System.out.println("stringbuilder:"+stringbuilder.length());
}
结果
String:17530
stringbuffer:100001
stringbuilder:99752
可见String 和 StringBuider是非线程安全的 Stringbuffer是线程安全的
分析:String追加字符串的过程是JVM又创建了一个新的对象,然后再把原来的string的值和“”内的值加起来再赋值给新的string
所以该过程缓慢而且非线程安全,StringBuider和Stringbuffer追加字符串是在同一个对象上操作,所以执行速度快,两者append函数的具体实现如下
@Override
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
可见StringBuffer函数上加了synchronized关键字所以是线程安全,这也是他速度较StringBuilder为慢的原因
本文对比分析了Java中String、StringBuffer和StringBuilder三种字符串类在速度和线程安全性上的表现。通过实验发现,StringBuilder在速度上最优,但不支持线程安全;StringBuffer虽然次之,但在多线程环境下保证了线程安全。
812

被折叠的 条评论
为什么被折叠?



