字符串拼接方法性能对比和分析
对字符串进行拼接主要有三种方法:
1.加号
2.concat方法
3.StringBuilder或者StringBuffer的append方法
下面看下性能对比,测试方法为各循环十万次,对比耗费时间。
测试性能
1.”+"拼接
long start = System.currentTimeMillis();String str = "j";for (int i = 0; i < 100000; i++) {str += "a";}long end = System.currentTimeMillis();System.out.println("执行时间" + (end - start));
2.concat方法
long start = System.currentTimeMillis();String str = "j";for (int i = 0; i < 100000; i++) {str = str.concat("a");}long end = System.currentTimeMillis();System.out.println("执行时间" + (end - start));
3.StringBuilder的append方法
long start = System.currentTimeMillis();StringBuilder sb = new StringBuilder("j");for (int i = 0; i < 100000; i++) {sb.append("a");}String str = sb.toString();long end = System.currentTimeMillis();System.out.println("执行时间" + (end - start));
结论:append最快,concat其次,加号最慢。
分析
1.加号拼接基本等同StringBulider的append方法,但为啥耗费时间远大于append?
str = new StringBuilder("j").append("a").toString();
因为每次循环都要创建StringBuilder对象,都要调用toString方法转换为字符串。
2.concat方法分析,下面是concat的源码。
public String concat(String str) {if (str.isEmpty()) {return this;}int len = value.length;int otherLen = str.length();char buf[] = Arrays.copyOf(value, len + otherLen);str.getChars(buf, len);return new String(buf, true);}
其实就是一个数组拷贝,它本身是很快的,但是最后都要new一个String对象,循环十万次就是new十万个对象。
3.append方法分析
public AbstractStringBuilder append(String str) {if (str == null)return appendNull();int len = str.length();ensureCapacityInternal(count + len);str.getChars(0, len, value, count);count += len;return this;}
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {if (srcBegin < 0) {throw new StringIndexOutOfBoundsException(srcBegin);}if (srcEnd > value.length) {throw new StringIndexOutOfBoundsException(srcEnd);}if (srcBegin > srcEnd) {throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);}System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);}
本质上就是加长数组长度,数组拷贝,没有new任何对象。最后循环完毕用toString方法返回字符串。
以上就是性能分析,但在我们平时开发中,没有如此大量的拼接处理,加号拼接更友好和阅读,也没有什么问题。