在Java中有五种字符串的连接方式:+,concat(String的方法),join(StringUtils的方法),append(StringBuffer的方法),append(StringBuilder的方法)。下面我们来看看五种运行的结果,用结果说话
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class testString {
public void testPlus() {
String s = "";
long ts = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
s = s + String.valueOf(i);
}
long te = System.currentTimeMillis();
System.out.print("plus:");
System.out.println(te - ts);
}
public void testConcat() {
String s = "";
long ts = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
s = s.concat(String.valueOf(i));
}
long te = System.currentTimeMillis();
System.out.print("concat:");
System.out.println(te - ts);
}
public void testJoin() {
List<String> list = new ArrayList<String>();
long ts = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
list.add(String.valueOf(i));
}
StringUtils.join(list, "");
long te = System.currentTimeMillis();
System.out.print("join:");
System.out.println(te - ts);
}
public void testStringBuffer() {
StringBuffer sb = new StringBuffer();
long ts = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
sb.append(String.valueOf(i));
}
sb.toString();
long te = System.currentTimeMillis();
System.out.print("StringBUffer.append:");
System.out.println(te - ts);
}
public void testStringBuilder() {
StringBuilder sb = new StringBuilder();
long ts = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
sb.append(String.valueOf(i));
}
sb.toString();
long te = System.currentTimeMillis();
System.out.print("StringBuilder.append:");
System.out.println(te - ts);
}
public static void main(String[] args) {
testString ts = new testString();
ts.testPlus();
ts.testConcat();
ts.testJoin();
ts.testStringBuffer();
ts.testStringBuilder();
}
}
运行结果如下:
plus:17219
concat:6898
join:45
StringBUffer.append:13
StringBuilder.append:10
由结果可以看出:append(StringBuilder)>append(StringBuffer)>join>concat>+;至于为什么,写起来很麻烦,我就不写了,大家可以实际运行下代码,再去探讨