Java里面字符串拼接,估计是使用的最多的,经常使用的就是几种方式,谁的效率高呢:
1,直接使用“+”来拼接字符串
2,使用字符串自带的contact()方法
3,使用StringBuffer的append()和toString()方法
4,使用StringBuilder的append()和toString()方法
暂时就这么几个,若是再有的话,再继续比较。
下面看看,他们一起运行的时间占比截图
使用的测试代码:
text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
private static final String TTM = "0|pr";
public static void main(String[] args) {
testStringContact();
}
private static void testStringContact() {
String[] split = TTM.split("\\|");
int length =split.length;
while (true){
String s = testAdd(split, length);
String s1 = testStringBuilderAppend(split, length);
String s2 = testStringBufferAppend(split, length);
String s3 = testContact(split, length);
}
}
private static String testContact(String[] split, int length) {
String result = "";
for (int i = 0; i < length; i++) {
result = result.concat(split[i]);
}
return result;
}
private static String testStringBufferAppend(String[] split, int length) {
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < length; i++) {
stringBuffer.append(split[i]);
}
return stringBuffer.toString();
}
private static String testStringBuilderAppend(String[] split, int length) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
stringBuilder.append(split[i]);
}
return stringBuilder.toString();
}
private static String testAdd(String[] split, int length) {
String result = null;
for (int i = 0; i < length; i++) {
result +=split[i];
}
return result;
}
有么有比这个builder还快的呢?





评论
登录后即可评论
分享你的想法,与作者互动
暂无评论