Suppose our application have only one thread. and we are using StringBuffer
then what is the problem?
I mean if StringBuffer
can handle multiple threads through synchronization, what is the problem to work with single thread?
Why use StringBuilder
instead?
StringBuffers
are thread-safe, meaning that they have synchronized methods to control access so that only one thread can access a StringBuffer object's synchronized code at a time. Thus, StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time.
StringBuilder's
access is not synchronized so that it is not thread-safe. By not being synchronized, the performance of StringBuilder can be better than StringBuffer. Thus, if you are working in a single-threaded environment, using StringBuilder instead of StringBuffer may result in increased performance. This is also true of other situations such as a StringBuilder local variable (ie, a variable within a method) where only one thread will be accessing a StringBuilder object.
So, prefer StringBuilder
because,
Check this out :