Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Strings VS String Array VS Stringbuilder [duplicate]

Tags:

java

Which is the best one to choose to store list of string on the basis of performance.

Which one offers the best performance.

Thanks.

like image 359
Kathir Avatar asked Dec 11 '13 06:12

Kathir


People also ask

Are StringBuilder and String identical types?

StringBuilder and String are completely different objects.

What are the differences between String and StringBuilder you need to list a few differences?

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.

Is String builder a list?

StringBuilder is a mutable String. You can think of it as List<Character> .

What is the best reason for StringBuilder instead of String?

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.


2 Answers

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.

like image 159
bcorso Avatar answered Sep 21 '22 12:09

bcorso


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.

like image 34
Aniket Thakur Avatar answered Sep 19 '22 12:09

Aniket Thakur