StringBuilder sb = new StringBuilder();
while (read line from File) {
sb.append(line).append("\n");
}
or
List <String> lines = ArrayList<String>();
while (read line from File){
lines.add(line);
}
Which of the above is more efficient ?
StringBuilder sb = new StringBuilder();
while (read line from File) {
sb.append(line).append("\n");
}
or
List <String> lines = ArrayList<String>();
while (read line from File){
lines.add(line);
}
Which of the above is more efficient ?
That depends a bit on what you do next. Performance wise, the ArrayList
wins since it allocates just pointers to existing strings a few times. The StringBuffer
might need less memory but it copies all the strings (and sometimes itself when it has to extend its buffer) so it's slower.
I say "might need less memory" since the buffer doubles size each time it's full. Let's assume the buffer is 1024, 1020 characters are in it and you need to add another 5. That means it now needs 2048 (instead of 1025 characters), so it "wastes" 1023 characters.
The list also doubles in size but since the items might be smaller (this statement depends on the average line length), it should usually take less memory. Also copying the smaller pointers in the list is faster (this happens every time the internal array of the list is full).
StringBuilder is more efficient in terms of memory in most cases.
With ArrayList you keep all of the Strings in memory, with StringBuilder you keep only the characters in a char array, because the actual Strings will be GCed. Thus, if you have 10000 Strings you have a difference of memory of 10000 * difference in memory between a String and it's corresponding characters (which are objects in String class itself, like the lock, length, hash and eventually others).
To be noted that StringBuilder is also expected to be a little bit slower; like everything in Computer Science there is a trade-off between CPU and memory.
Array List should have more memory footprints as by default ArrayList will reserve memory for 10 objects while stringbuilder will not. Since string object appended to stringbuilder or added to arraylist will occupy same memory, difference lies in the non utilisation of the reserved space created by Arraylist.
In terms of accesiblity arraylist offers more options as compared to StringBuilder