Stringbuffer,Stringbuilder when to use? [duplicate]
Asked Answered
C

2

1

Possible Duplicate:
StringBuilder and StringBuffer in Java

Criteria to choose among StringBuffer and StringBuilder

Collencollenchyma answered 18/10, 2012 at 18:25 Comment(0)
P
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...

Picayune answered 18/10, 2012 at 18:26 Comment(7)
+1 IMHO, If you think you need to share a StringBuffer between threads you have serious design issue.Harr
Dont u think that using StringBuilder will un-necessarily use the heap space?Graham
@TheHunter: Compared with doing what? Why would you expect StringBuilder to use more heap space than StringBuffer?Picayune
@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.Graham
@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.Graham
@TheHunter: I think you've missed the point of the question - it's primarily comparing StringBuffer and StringBuilder, not String and StringBuilder. And not all strings are in the string pool, either - I suspect you've misunderstoo how the string pool works. I would only use StringBuilder when building a string...Picayune
@TheHunter: Note that the original question - when I answered it - didn't even have String in the mix. Another user decided to add that (against the editorial guidelines, IMO). I've effectively reverted that edit to go back to what the OP asked, but better formatted...Picayune
D
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

Danziger answered 18/10, 2012 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.