1

My requirement is to store the large chunk of data (String value) but i am confused which one is better to use. I only want to append the incoming data.

e.g. String str1 = "abc"
     String str2 = "123";
     String Str3 = "xyz"; 

 suppose i am appending/ adding to  (Sbuilder/SBuffer/ vector/ ArrayList)  
 one after another, 
         e.g.  str1, str2 str3    then output must be    "abc123xyz"
               str2, str1,str3    output must be         "123abcxyz"

5 Answers 5

2

Use StringBuilder and ArrayList

StringBuffer and Vector have thread synchronization that adds overhead (unless you need it, but even then there's ways to add that to the newer classes)

Sign up to request clarification or add additional context in comments.

Comments

2

From the javadoc for StringBuffer:

The StringBuilder 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.

Also, I think the Vector is backed internally by an Array as well, and is pretty much deprecated. If you want fast appends then you might want to take a look at LinkedList (it is slightly faster than ArrayList for pure appends because you don't have to grow the backing Array periodically).

However, if this is just for sequences of characters then the StringBuilder is optimized for exactly this case, and you shouldn't muck around with Collections with all of their overhead.

2 Comments

Thanks bdares ! the sequences of characters is important in my case and ofcourse the size at runtime. so i think StringBuilder would be nice to use.
don't know why, vector is used in the project for the same, but i feel vector isn't the right choice for concating the String only.
0

If you don't need to synchronize you can avoid StringBuffer and Vector and prefer StringBuilder and ArrayList instead.

Whether to use StringBuilder or ArrayList depends on your requirements. If you just want to concatenate the strings SB is enough.

Comments

0

If data size is variable in that case we used StringBuffer because the StringBuffer class is designed to create and manipulate dynamic string information. The memory allocated to the object is automatically.

Comments

0

If you are doing this inside a single thread you will want to use a StringBuilder over anything when all you want to achieve is string concatenation; for multiple types use an ArrayList.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.