在Java里String串的拼接方式有5种
join
concat
StringBuffer(线程安全)
StringBuilder
package com.main;
import java.util.ArrayList;
import java.util.List;
public class TestString {
public void testPlus() {
String s = "";
long ts = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
s = s + String.valueOf(i);
}
long te = System.currentTimeMillis();
System.out.println("+ cost {"+ (te - ts)+"} ms");
}
public void testConcat() {
String s = "";
long ts = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
s = s.concat(String.valueOf(i));
}
long te = System.currentTimeMillis();
System.out.println("concat cost {"+ (te - ts)+"} ms");
}
public void testJoin() {
List<String> list = new ArrayList<String>();
long ts = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
list.add(String.valueOf(i));
}
String.join("-", list);
long te = System.currentTimeMillis();
System.out.println("join cost {"+ (te - ts)+"} ms");
}
public void testStringBuffer() {
StringBuffer sb = new StringBuffer();
long ts = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
sb.append(String.valueOf(i));
}
sb.toString();
long te = System.currentTimeMillis();
System.out.println("StringBuffer cost {"+ (te - ts)+"} ms");
}
public void testStringBuilder() {
StringBuilder sb = new StringBuilder();
long ts = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
sb.append(String.valueOf(i));
}
sb.toString();
long te = System.currentTimeMillis();
System.out.println("StringBuilder cost {"+ (te - ts)+"} ms");
}
public void testStringBufferWith50000000() {
StringBuffer sb = new StringBuffer();
long ts = System.currentTimeMillis();
for (int i = 0; i < 50000000; i++) {
sb.append(String.valueOf(i));
}
sb.toString();
long te = System.currentTimeMillis();
System.out.println("StringBuffer50000000 cost {"+ (te - ts)+"} ms");
}
public void testStringBuilderWith50000000() {
StringBuilder sb = new StringBuilder();
long ts = System.currentTimeMillis();
for (int i = 0; i < 50000000; i++) {
sb.append(String.valueOf(i));
}
sb.toString();
long te = System.currentTimeMillis();
System.out.println("StringBuilder50000000 cost {"+ (te - ts)+"} ms");
}
}
执行结果
+ cost {2789} ms
concat cost {1088} ms
join cost {8} ms
StringBuffer cost {4} ms
StringBuilder cost {3} ms
StringBuffer50000000 cost {3091} ms
StringBuilder50000000 cost {2726} ms
网友评论