I just ran some benchmarks as I was interested in what the fastest way would be.
I ran 4 different methods, each 1.000.000 ( 1 million ) times for good measure.
Side note:
- The ArrayList was filled with 2710 Characters,
- the input was some random JSON string i had lying around,
- my computer is not the strongest ( Cpu: AMD Phenom II X4 955 @3.20 GHz ).
- Convert into Array, then into String ( adarshr's Answer )
char[] cs = new char[chars.size()];
for(int x = 0; x < cs.length; x++){
cs[x] = chars.get(x);
}
String output = new String(cs);
Time: 7716056685 Nanoseconds or ~7.7 Seconds / Index: 1
- Use a StringBuilder with predefined size to collect each Character ( Sean Owen's Answer )
StringBuilder result = new StringBuilder(chars.size());
for(Character c : chars){
result.append(c);
}
String output = result.toString();
Time: 77324811970 Nanoseconds or ~77.3 Seconds / Index: ~10
- Use a StringBuilder without predefined size to collect each Character
StringBuilder result = new StringBuilder();
for(Character c : chars){
result.append(c);
}
String output = result.toString();
Time: 87704351396 Nanoseconds or ~87.7 Seconds / Index: ~11,34
- Create an empty String and just += each Character ( Jonathan Grandi's Answer )
String output = "";
for(int x = 0; x < cs.length; x++){
output += chars.get(x);
}
Time: 4387283410400 Nanoseconds or ~4387.3 Seconds / Index: ~568,59
I actually had to scale this one down. This method was only run 10000 times, which already took ~43 Seconds, I just multiplied the result with 100 to get an approximation of 1.000.000 runs
Conclusion:
Use the "Convert into Array, then into String" method... it's fast... On the other hand, I wouldn't have thought the += operation to be so slow...
How I tested:
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();