注意:在Java8中默认使用StringBuilder进行字符串进行拼接
下面代码对字符串进行10000次加号连接和StringBuilder连接操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class StringBuilderTest { public static void main(String[] args){ long time = System.currentTimeMillis(); System.out.println("begin: " + time); String str = ""; for(int i=0; i<10000; i++){ str = str + "a1" + 1 + "a2"; } long time1 = System.currentTimeMillis(); StringBuilder sb = new StringBuilder(); for(int i=0; i<10000; i++){ //sb.delete(0, sb.length()); sb.append("a1"); sb.append(1); sb.append("a2"); } long time2 = System.currentTimeMillis(); System.out.println(str); System.out.println(sb.toString()); System.out.println("加号耗时: " + (time1 - time)); System.out.println("StringBuilder耗时: " + (System.currentTimeMillis() - time1)); } } |
最后得到的结果如下:
1 2 |
加号耗时: 563 StringBuilder耗时: 7 |
由此可见效率差了80倍
注意:
- StringBuffer为线程安全的字符串操作类,由于需要处理多线程同步问题,效率比StringBuilder要低