1

Possible Duplicate:
StringBuilder and StringBuffer in Java

Criteria to choose among StringBuffer and StringBuilder

Andrew
49.8k15 gold badges99 silver badges145 bronze badges
asked Oct 18, 2012 at 18:25
0

2 Answers 2

7

If you're definitely using Java 5 or higher, and you definitely don't need to share the object between threads (I can't remember ever needing to do so), StringBuilder is a better bet.

Basically you should almost always use StringBuilder when you can, to avoid pointless synchronization. Admittedly the way most VMs handle uncontended synchronization is extremely efficient, but if you don't need it in the first place...

answered Oct 18, 2012 at 18:26

7 Comments

+1 IMHO, If you think you need to share a StringBuffer between threads you have serious design issue.
Dont u think that using StringBuilder will un-necessarily use the heap space?
@TheHunter: Compared with doing what? Why would you expect StringBuilder to use more heap space than StringBuffer?
@JonSkeet When you do not need to share objects between threads(i,e when your string is not being accessed by multiple threads), don't you think that just using String will be a much better option than using StringBuilder? As StringBuilder stores its objects directly into the heap space.
@JonSkeet just to add...String will store its objects into the string pool and thus saving the overall heap space. But StringBuilder will unnecessarily use the heap space.
|
6

StringBuilder methods are not synchronized, so when you are not concerned with multithreading part you can use it, as it would be fast.

StringBuffer on the other hand have all its method synchronized, and hence is thread safe.

You can go through this post: - Difference between StringBuilder and StringBuffer

answered Oct 18, 2012 at 18:26

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.