我只是运行了一些基准测试,因为我对最快的方法很感兴趣。
我运行了 4 种不同的方法,每种方法都运行了 1.000.000(100 万)次。
旁注:
- ArrayList 填充了 2710 个字符,
- 输入是我放置的一些随机 JSON 字符串,
- 我的电脑不是最强的(CPU:AMD Phenom II X4 955 @3.20 GHz)。
- 先转换成数组,再转换成字符串(adarshr 的回答)
char[] cs = new char[chars.size()];
for(int x = 0; x < cs.length; x++){
cs[x] = chars.get(x);
}
String output = new String(cs);
时间:7716056685 纳秒或 ~7.7 秒/索引:1
- 使用具有预定义大小的 StringBuilder 来收集每个字符(Sean Owen 的回答)
StringBuilder result = new StringBuilder(chars.size());
for(Character c : chars){
result.append(c);
}
String output = result.toString();
时间:77324811970 纳秒或~77.3 秒/索引:~10
- 使用 StringBuilder 没有预定义的大小来收集每个字符
StringBuilder result = new StringBuilder();
for(Character c : chars){
result.append(c);
}
String output = result.toString();
时间:87704351396 纳秒或~87.7 秒/索引:~11,34
- 创建一个空字符串,然后 += 每个字符(Jonathan Grandi 的答案)
String output = "";
for(int x = 0; x < cs.length; x++){
output += chars.get(x);
}
时间:4387283410400 纳秒或~4387.3 秒/索引:~568,59
我实际上不得不缩小这个比例。这个方法只运行了 10000 次,已经花费了大约 43 秒,我只是将结果乘以 100 得到一个近似值 1.000.000 次运行
结论:
使用“先转换成数组,再转换成字符串”的方法……很快……另一方面,我没想到+=操作这么慢……
我是如何测试的:
final String jsonExample = new String("/* Random Json String here */");
final char[] charsARRAY = jsonExample.toCharArray();
final ArrayList<Character> chars = new ArrayList<Character>();
for(int i = 0; i < charsARRAY.length; i++){
chars.add(charsARRAY[i]);
}
final long time1, time2;
final int amount = 1000000;
time1 = System.nanoTime();
for(int i = 0; i < amount; i++){
// Test method here
}
time2 = System.nanoTime();