Which is the best one to choose to store list of string on the basis of performance.
Which one offers the best performance.
Thanks.
StringBuilder and String are completely different objects.
String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer. String concatenation operator (+) internally uses StringBuffer or StringBuilder class.
StringBuilder is a mutable String. You can think of it as List<Character> .
This is because String is immutable - it cannot change its internal state. On the other hand StringBuilder is mutable. When you call append(..) it alters the internal char array, rather than creating a new string object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With