What is the main difference between StringBuffer
and StringBuilder
?
Is there any performance issues when deciding on any one of these?
First lets see the similarities: Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.
Differences: StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.
Meaning of synchronized (synchronization): When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.
Which one to use when? StringBuilder : When you need a string, which can be modifiable, and only one thread is accessing and modifying it. StringBuffer : When you need a string, which can be modifiable, and multiple threads are accessing and modifying it.
Note : Don't use StringBuffer unnecessarily, i.e., don't use it if only one thread is modifying and accessing it because it has lot of locking and unlocking code for synchronization which will unnecessarily take up CPU time. Don't use locks unless it is required.