> 字符串拼接一般使用“+”,但是“+”不能满足大批量数据的处理,Java中有以下五种方法处理字符串拼接,各有优缺点,程序开发应选择合适的方法实现。
1. 加号 “+”
2. String contact() 方法
3. StringUtils.join() 方法
4. StringBuffer append() 方法
5. StringBuilder append() 方法
ps:org.apache.commons.lang.StringUtils类是用于操作Java.lang.String类的
> 字符串拼接一般使用“+”,但是“+”不能满足大批量数据的处理,Java中有以下五种方法处理字符串拼接,各有优缺点,程序开发应选择合适的方法实现。
1. 方法1 加号 “+” 拼接 和 方法2 String contact() 方法 适用于小数据量的操作,代码简洁方便,加号“+” 更符合我们的编码和阅读习惯;
2. 方法3 StringUtils.join() 方法 适用于将ArrayList转换成字符串,就算90万条数据也只需68ms,可以省掉循环读取ArrayList的代码;
3. 方法4 StringBuffer append() 方法 和 方法5 StringBuilder append() 方法 其实他们的本质是一样的,都是继承自AbstractStringBuilder,效率最高,大批量的数据处理最好选择这两种方法。
4. 方法1 加号 “+” 拼接 和 方法2 String contact() 方法 的时间和空间成本都很高(分析在本文末尾),不能用来做批量数据的处理。
>然后就是最关心的使用方法了
import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; public class TestString { private static final int max = 100; public void testPlus() { System.out.println(">>> testPlus() <<<"); String str = ""; long start = System.currentTimeMillis(); for (int i = 0; i < max; i++) { str = str + "a"; } long end = System.currentTimeMillis(); long cost = end - start; System.out.println(" {str + \"a\"} cost=" + cost + " ms"); } public void testConcat() { System.out.println(">>> testConcat() <<<"); String str = ""; long start = System.currentTimeMillis(); for (int i = 0; i < max; i++) { str = str.concat("a"); } long end = System.currentTimeMillis(); long cost = end - start; System.out.println(" {str.concat(\"a\")} cost=" + cost + " ms"); } public void testJoin() { System.out.println(">>> testJoin() <<<"); long start = System.currentTimeMillis(); List<String> list = new ArrayList<String>(); for (int i = 0; i < max; i++) { list.add("a"); } long end1 = System.currentTimeMillis(); long cost1 = end1 - start; StringUtils.join(list, ""); long end = System.currentTimeMillis(); long cost = end - end1; System.out.println(" {list.add(\"a\")} cost1=" + cost1 + " ms"); System.out.println(" {StringUtils.join(list, \"\")} cost=" + cost + " ms"); } public void testStringBuffer() { System.out.println(">>> testStringBuffer() <<<"); long start = System.currentTimeMillis(); StringBuffer strBuffer = new StringBuffer(); for (int i = 0; i < max; i++) { strBuffer.append("a"); } strBuffer.toString(); long end = System.currentTimeMillis(); long cost = end - start; System.out.println(" {strBuffer.append(\"a\")} cost=" + cost + " ms"); } public void testStringBuilder() { System.out.println(">>> testStringBuilder() <<<"); long start = System.currentTimeMillis(); StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < max; i++) { strBuilder.append("a"); } strBuilder.toString(); long end = System.currentTimeMillis(); long cost = end - start; System.out .println(" {strBuilder.append(\"a\")} cost=" + cost + " ms"); } }> 查看源代码,以及简单分析
String contact 和 StringBuffer,StringBuilder 的源代码都可以在Java库里找到,有空可以研究研究。
1. 其实每次调用contact()方法就是一次数组的拷贝,虽然在内存中是处理都是原子性操作,速度非常快,但是,最后的return语句会创建一个新String对象,限制了concat方法的速度。
public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); str.getChars(buf, len); return new String(buf, true); }
2. StringBuffer 和 StringBuilder 的append方法都继承自AbstractStringBuilder,整个逻辑都只做字符数组的加长,拷 贝, 到最后也不会创建新的String对象,所以速度很快,完成拼接处理后在程序中用strBuffer.toString()来得到最终的字符串。
public AbstractStringBuilder append(String str) { if (str == null) str = "null"; int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; return this; }
private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code if (minimumCapacity - value.length > 0) expandCapacity(minimumCapacity); } /** * This implements the expansion semantics of ensureCapacity with no * size check or synchronization. */ void expandCapacity(int minimumCapacity) { int newCapacity = value.length * 2 + 2; if (newCapacity - minimumCapacity < 0) newCapacity = minimumCapacity; if (newCapacity < 0) { if (minimumCapacity < 0) // overflow throw new OutOfMemoryError(); newCapacity = Integer.MAX_VALUE; } value = Arrays.copyOf(value, newCapacity); }
3. 字符串的加号“+” 方法, 虽然编译器对其做了优化,使用StringBuilder的append方法进行追加,但是每循环一次都会创建一个StringBuilder对象,且都会调用toString方法转换成字符串,所以开销很大。
如JVM对于“+”是这样处理的,首先创建一个String对象str,并把“abc”赋值给str,然后在第三行中,其实JVM又创建了一个新的对象也名为str,然后再把原来的str的值和“de”加起来再赋值给新的str,而原来的str就会被JVM的垃圾回收机制(GC)给回收掉了,所以,str实际上并没有被更改,也就是前面说的String对象一旦创建之后就不可更改了。所以,Java中对String对象进行的操作实际上是一个不断创建新的对象并且将旧的对象回收的一个过程,所以执行速度很慢。
注:执行一次字符串“+”,相当于 str = new StringBuilder(str).append("a").toString();
4. 常说拿空间换时间,反过来是不是拿时间换到了空间呢,但是在这里,其实时间是消耗在了重复的不必要的工作上(生成新的对象,toString方法),所以对大批量数据做处理时,加号“+” 和 contact 方法绝对不能用,时间和空间成本都很高。
ps:本文大都出自https://www.cnblogs.com/twzheng/p/5923642.html