珠海找工作哪个网站好,怎么找到仿牌外贸出口公司的网站,访问国外网站的软件,设计师培训有哪些课程对字符串进行拼接主要有三种方法#xff1a; 1.加号 2.concat方法 3.StringBuilder或者StringBuffer的append方法 下面看下性能对比#xff0c;测试方法为各循环十万次#xff0c;对比耗费时间。
测试性能
1.”拼接 long start System.currentTimeMillis();String …对字符串进行拼接主要有三种方法 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方法返回字符串。 以上就是性能分析但在我们平时开发中没有如此大量的拼接处理加号拼接更友好和阅读也没有什么问题。