Which is the best one to choose to store list of string on the basis of performance.
Which one offers the best performance.
Thanks.
Which is the best one to choose to store list of string on the basis of performance.
Which one offers the best performance.
Thanks.
ArrayList
is a good general purpose List
and will usually out-perform an Array
or LinkedList
. Here is the breakdown in terms of time complexity (V
is the type, i
is an index):
Type | add(V) | remove(V) | get(i) |
-------------------------------------------
Array | O(n) | O(n) | O(1) |
ArrayList | O(1) | O(n) | O(1) |
LinkedList | O(1) | O(1) | O(n) |
In general you can use this rule:
Array: Use if you know the exact number of elements and don't need to add or remove elements.
List: Use if you don't know the exact number of elements and need to add or remove elements.
StringBuilder
is completly different. StringBuilder
is a mutable String. You can think of it as List<Character>
. In that sense, it is probably not what you need so to compare it to List<String>
or String[]
is probably not benificial.
List of String literals before java 7 will just consume your permgen Area which may led to JVM crash. So if you have too many String better go for Stringbuilder. Stringbuilder internally uses char array. However using Stringbuilder for storing list of String you may have to use special character for separation and then split() to retrieve back your list.
Better alternative would be to go for an String array. As mentioned earlier even Stringbuilder uses an char array. So if you are sure you want to store list of String this would be good option. But if this is the only goal I would say why not use ArratList... you don't have to bother about the size of the array.
Always use StringBuilder
when constructing large strings. Although the speed difference is not noticeable, this is the most efficient.
I've also heard somewhere that Java uses a builder internally when you use the plus operator on strings. Although I'm uncertain, it is highly unlikely.
String
is an immutable class, it can't be changed. StringBuilder
is a mutable class that can be appended to, characters replaced or removed and ultimately converted to a String
.
Note that if you are using Java 5 or newer, you should use StringBuilder
instead of StringBuffer
. From the API documentation:
As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread,
StringBuilder
. TheStringBuilder
class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
For More