What is the main difference between StringBuffer
and StringBuilder
?
Is there any performance issues when deciding on any one of these?

- 46,613
- 43
- 151
- 237

- 18,957
- 5
- 20
- 11
33 Answers
StringBuffer
is synchronized, StringBuilder
is not.

- 1,255
- 1
- 11
- 29

- 60,628
- 22
- 121
- 123
-
251and StringBuilder is intended as a drop in replacement for StringBuffer where synchronisation is not required – Joel Dec 23 '09 at 08:52
-
100and synchronization is virtually never required. If someone wants to synchronize on a StringBuilder, they can just surround the entire block of code with a synchronized (sb) { } on the instance – locka Apr 24 '13 at 16:06
-
25@locka I would argue that StringBuffer is never a good idea (unless you have an API which requires it) http://vanillajava.blogspot.de/2013/04/why-synchronized-stringbuffer-was-never.html – Peter Lawrey Sep 04 '13 at 10:21
-
10Only place I see for a StringBuffer is console like output and various logging utility: many thread may output in conflict. Since you don't want 2 output to get mixed up... but usually synchronizing at StringBuffer level is too low level, you will want to synchronize at an appender like levelm so locka answer is the best and StringBuffer should be deprecated. It would save code review time with newbies. – Remi Morin Feb 17 '14 at 16:10
-
http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html – Praveen P Moolekandathil May 29 '15 at 10:03
-
24Good mnemonic for those who mix these two - BuFFer was First, older and therefore synchronized implementation. Newer Builder class uses Builder pattern and is asynchronous. – Datageek Jan 16 '16 at 17:50
-
But `StringBuffer` is slower than `StringBuilder`. You choose the one you perfer based on what kind of applications you work on – tqjustc Mar 25 '16 at 23:05
-
4Another difference is that `StringBuffer` can be used with `Matcher#appendReplacement`, whereas `StringBuilder` **cannot**. This is a very annoying API difference, especially because `Matcher` is not thread safe so there is no need for `appendReplacement` to require synchronization. – Max Apr 14 '16 at 21:10
-
[java.lang.StringBuffer : All methods except the Constructor are synchronized](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/StringBuffer.java#StringBuffer.append%28long%29) Vs [java.lang.StringBuilder : All of them are normal (non-synchronized) methods](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/StringBuilder.java#StringBuilder.append%28java.lang.String%29) – Abhijeet Sep 18 '16 at 10:59
-
To find more details about What actual cause the StringBuilder fails in multi threading environment I have asked a question that could be helpful https://stackoverflow.com/questions/31375718/what-actualy-casuse-the-stringbuilder-fails-in-multi-threading-envoirmnet – Alireza Fattahi Dec 21 '16 at 10:06
-
1Why does the newest edit say, that StringBuilder is an immutable object? Neither is it immutable, nor is it an object, it is a class. This should not be part of the top answer. – Raimund Krämer Nov 09 '17 at 08:21
-
@D.Everhard Agreed, actually I also got confused. This should be corrected. – foxt7ot Nov 16 '17 at 15:43
-
@sblundy StringBuilder is not immutable, shocked as no one pointed out – DnA Nov 17 '17 at 17:54
StringBuilder
is faster than StringBuffer
because it's not synchronized
.
Here's a simple benchmark test:
public class Main {
public static void main(String[] args) {
int N = 77777777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = N; i --> 0 ;) {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = N; i > 0 ; i--) {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
}
}
A test run gives the numbers of 2241 ms
for StringBuffer
vs 753 ms
for StringBuilder
.

- 9,964
- 5
- 76
- 81

- 376,812
- 128
- 561
- 623
-
12I changed the string literal to something larger: "the quick brown fox " and got more interesting results. Basically, they are about as fast. I actually ran out of memory so I had to remove a few sevens. Explanation: the synchronization is optimized away by hotspot. You are basically just measuring the time it takes hotspot to do this (and probably some more optimizations). – Jilles van Gurp Aug 26 '12 at 15:25
-
Agree with Alfredo. Adding to Jiles comment, when used with one char string ("A"), the ration is like 2 x 1 (2 for StringBuffer). using more than 3 chars and I got "OutOfMemoryError"! (-Xms512m/-Xmx1024m) – Ricardo Rivaldo Apr 02 '13 at 14:27
-
12You need to warm up before. This test is unfair to StringBuffer. Also, it would be good if it actually appended something. Actually, I flipped the test, and appended a random string and got the opposite test. Goes to say, that one cannot trust simple benchmarks. The opposite shows StringBuffer is faster. 5164 for StringBuilder vs 3699 for StringBuffer http://hastebin.com/piwicifami.avrasm – mjs Nov 03 '15 at 11:34
-
If one tries to run the tests over and over again, in different orders, the difference is hardly noticable, and not clear, quite frankly on who is the winner. – mjs Nov 03 '15 at 11:47
-
84This is the first time I see `--> 0` in a loop. Took me a moment to realize what it means. Is this something that is actually used in practice instead of the usual `...; i > 0; i--` syntax? – Raimund Krämer Dec 15 '15 at 12:25
-
1Yeah Even i have not used such for constructs --> 0 , I tried using `{for (int i = 0; i --> N ;)}` which did not work ? . – avinashkr Aug 02 '16 at 09:13
-
25That `i -->` is really annoying syntax-wise... I thought it was an arrow at first because of the comments about ASCII art. – Sameer Puri Aug 10 '16 at 19:14
-
1@D.Everhard and the others: [This](http://stackoverflow.com/questions/1642028/) may be an interesting read to you. – Adowrath Jan 29 '17 at 22:07
-
17Others conclude with different results: http://alblue.bandlem.com/2016/04/jmh-stringbuffer-stringbuilder.html. Benchmarks should really be done with JMH, not with a simple `main()` Also, your benchmark is unfair. There's no warmup. – Lukas Eder Jun 02 '17 at 09:03
-
2what a nice world it would be if `for (int i = N; i --> 0 ;)` counted as a party trick – lelloman Jun 19 '17 at 08:00
-
This benchmark is inaccurate, when the code is inside the first looad, the JVM needs to load arrays internally, since thats used inside stringbuilder itself, but it doesn't do this in de stringbuilder test, as it already loaded it – Ferrybig Feb 15 '19 at 15:47
Basically, StringBuffer
methods are synchronized while StringBuilder
are not.
The operations are "almost" the same, but using synchronized methods in a single thread is overkill.
That's pretty much about it.
Quote from StringBuilder API:
This class [StringBuilder] provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
So it was made to substitute it.
The same happened with Vector
and ArrayList
.

- 916
- 2
- 15
- 32

- 196,001
- 113
- 385
- 569
But needed to get the clear difference with the help of an example?
StringBuffer or StringBuilder
Simply use StringBuilder
unless you really are trying to share a buffer between threads. StringBuilder
is the unsynchronized (less overhead = more efficient) younger brother of the original synchronized StringBuffer
class.
StringBuffer
came first. Sun was concerned with correctness under all conditions, so they made it synchronized to make it thread-safe just in case.
StringBuilder
came later. Most of the uses of StringBuffer
were single-thread and unnecessarily paying the cost of the synchronization.
Since StringBuilder
is a drop-in replacement for StringBuffer
without the synchronization, there would not be differences between any examples.
If you are trying to share between threads, you can use StringBuffer
, but consider whether higher-level synchronization is necessary, e.g. perhaps instead of using StringBuffer, should you synchronize the methods that use the StringBuilder.
-
15The first good answer!! The point is "unless you are sharing a buffer between threads" – AlexWien Mar 20 '15 at 17:47
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.

- 562
- 3
- 11
- 22

- 4,684
- 35
- 29
-
2Just want to mention that StringBuffer's INDIVIDUAL method calls are thread-safe. But if you have multiple lines of code, use a synchronized code block to guarantee thread-safety, with some lock/monitor (as per usual...). Basically, don't just assume that using a thread-safe library immediately guarantees thread-safety in YOUR program! – Kevin Lee Mar 14 '14 at 18:39
In single threads, StringBuffer is not significantly slower than StringBuilder, thanks to JVM optimisations. And in multithreading, you can't use safely a StringBuilder.
Here is my test (not a benchmark, just a test) :
public static void main(String[] args) {
String withString ="";
long t0 = System.currentTimeMillis();
for (int i = 0 ; i < 100000; i++){
withString+="some string";
}
System.out.println("strings:" + (System.currentTimeMillis() - t0));
t0 = System.currentTimeMillis();
StringBuffer buf = new StringBuffer();
for (int i = 0 ; i < 100000; i++){
buf.append("some string");
}
System.out.println("Buffers : "+(System.currentTimeMillis() - t0));
t0 = System.currentTimeMillis();
StringBuilder building = new StringBuilder();
for (int i = 0 ; i < 100000; i++){
building.append("some string");
}
System.out.println("Builder : "+(System.currentTimeMillis() - t0));
}
Results :
strings: 319740
Buffers : 23
Builder : 7 !
So Builders are faster than Buffers, and WAY faster than strings concatenation. Now let's use an Executor for multiple threads :
public class StringsPerf {
public static void main(String[] args) {
ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
//With Buffer
StringBuffer buffer = new StringBuffer();
for (int i = 0 ; i < 10; i++){
executorService.execute(new AppendableRunnable(buffer));
}
shutdownAndAwaitTermination(executorService);
System.out.println(" Thread Buffer : "+ AppendableRunnable.time);
//With Builder
AppendableRunnable.time = 0;
executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < 10; i++){
executorService.execute(new AppendableRunnable(builder));
}
shutdownAndAwaitTermination(executorService);
System.out.println(" Thread Builder: "+ AppendableRunnable.time);
}
static void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // code reduced from Official Javadoc for Executors
try {
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (Exception e) {}
}
}
class AppendableRunnable<T extends Appendable> implements Runnable {
static long time = 0;
T appendable;
public AppendableRunnable(T appendable){
this.appendable = appendable;
}
@Override
public void run(){
long t0 = System.currentTimeMillis();
for (int j = 0 ; j < 10000 ; j++){
try {
appendable.append("some string");
} catch (IOException e) {}
}
time+=(System.currentTimeMillis() - t0);
}
}
Now StringBuffers take 157 ms for 100000 appends. It's not the same test, but compared to the previous 37 ms, you can safely assume that StringBuffers appends are slower with multithreading use. The reason is that the JIT/hotspot/compiler/something makes optimizations when it detects that there is no need for checking locks.
But with StringBuilder, you have java.lang.ArrayIndexOutOfBoundsException, because a concurrent thread tries to add something where it should not.
Conclusion is that you don't have to chase StringBuffers. And where you have threads, think about what they are doing, before trying to gain a few nanoseconds.

- 6,910
- 3
- 50
- 74
-
6You have forgotten to do "t0 = System.currentTimeMillis();" before doing StringBuilder test. So the figure displayed for StringBuilder is actually time it took to run stringbuffer AND stringbuilder test. Add this line and you'll see that StringBuilder IS faster about TWO TIMES. – Gena Batsyan Sep 26 '13 at 09:51
-
1You should use JMH for benchmarks. Your benchmark is really inaccurate. – Lukas Eder Jun 02 '17 at 09:21
StringBuilder was introduced in Java 1.5 so it won't work with earlier JVMs.
From the Javadocs:
StringBuilder class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

- 32,350
- 30
- 109
- 146

- 44,628
- 11
- 58
- 63
-
131.4 is at its End of Service Life, so it hardly seem worth worrying about pre-1.5. – Tom Hawtin - tackline Dec 14 '08 at 17:15
-
@tomHawtin-tackline not necessarily - there are enterprise products out there on pre 1.4 that most of us use daily. Also BlackBerry java is based on 1.4 and that is still very current. – Richard Le Mesurier Mar 13 '13 at 08:47
-
Pretty Good Question
Here are the differences, i have noticed :
StringBuffer :-
StringBuffer is synchronized
StringBuffer is thread-safe
StringBuffer is slow (try to write a sample program and execute it, it will take more time than StringBuilder)
StringBuilder:-
StringBuilder is not synchronized
StringBuilder is not thread-safe
StringBuilder performance is better than StringBuffer.
Common thing :-
Both have same methods with same signatures. Both are mutable.

- 12,978
- 3
- 74
- 76
StringBuffer
- Synchronized hence threadsafe
- Thread safe hence slow
StringBuilder
- Introduced in Java 5.0
- Asynchronous hence fast & efficient
- User explicitly needs to synchronize it, if he wants
- You can replace it with
StringBuffer
without any other change
-
NOTE: Only single operations are thread-safe, multiple operations are not. e.g if you call `append` twice, or `append` and `toString` isn't not safe. – Peter Lawrey Jan 13 '19 at 10:30
StringBuffer
StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .
because of this it does not allow two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .
But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus StringBuilder is faster than the StringBuffer when calling the same methods of each class.
StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes . String Buffer can be converted to the string by using toString() method.
StringBuffer demo1 = new StringBuffer(“Hello”) ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer(“Bye”);
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. StringBuilder is fast as it is not thread safe .
StringBuilder demo2= new StringBuilder(“Hello”);
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder(“Bye”);
// Above statement is right as it modifies the value which is allowed in the StringBuilder
Resource: String Vs StringBuffer Vs StringBuilder

- 2,863
- 32
- 41
-
-
I wouldn't agree that Strings and StringBuilders are "fast" and StringBuffers are "very slow". See the above answers. – kepe Feb 16 '19 at 14:55
StringBuilder
and StringBuffer
are almost the same. The difference is that StringBuffer
is synchronized and StringBuilder
is not. Although, StringBuilder
is faster than StringBuffer
, the difference in performance is very little. StringBuilder
is a SUN's replacement of StringBuffer
. It just avoids synchronization from all the public methods. Rather than that, their functionality is the same.
Example of good usage:
If your text is going to change and is used by multiple threads, then it is better to use StringBuffer
. If your text is going to change but is used by a single thread, then use StringBuilder
.

- 7,699
- 6
- 44
- 70

- 221
- 3
- 6
String
is an immutable.
StringBuffer
is a mutable and synchronized.
StringBuilder
is also mutable but its not synchronized.
-
Additionally StringBuffer locks Threads for access this thread safe data that's why operation goes slowly. StringBuilder does not lock thread and it runs in Multi Threading way that's why is fast. String - when you need not concatenate string this is good way, but when you need it use StringBuilder -> because String creates every time new Object in heap, but StringBuilder return same object... – Musa Feb 28 '18 at 21:46
The javadoc explains the difference:
This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

- 398,947
- 96
- 818
- 769
StringBuilder
(introduced in Java 5) is identical to StringBuffer
, except its methods are not synchronized. This means it has better performance than the latter, but the drawback is that it is not thread-safe.
Read tutorial for more details.

- 2,875
- 3
- 33
- 47

- 26,254
- 8
- 67
- 80
A simple program illustrating the difference between StringBuffer and StringBuilder:
/**
* Run this program a couple of times. We see that the StringBuilder does not
* give us reliable results because its methods are not thread-safe as compared
* to StringBuffer.
*
* For example, the single append in StringBuffer is thread-safe, i.e.
* only one thread can call append() at any time and would finish writing
* back to memory one at a time. In contrast, the append() in the StringBuilder
* class can be called concurrently by many threads, so the final size of the
* StringBuilder is sometimes less than expected.
*
*/
public class StringBufferVSStringBuilder {
public static void main(String[] args) throws InterruptedException {
int n = 10;
//*************************String Builder Test*******************************//
StringBuilder sb = new StringBuilder();
StringBuilderTest[] builderThreads = new StringBuilderTest[n];
for (int i = 0; i < n; i++) {
builderThreads[i] = new StringBuilderTest(sb);
}
for (int i = 0; i < n; i++) {
builderThreads[i].start();
}
for (int i = 0; i < n; i++) {
builderThreads[i].join();
}
System.out.println("StringBuilderTest: Expected result is 1000; got " + sb.length());
//*************************String Buffer Test*******************************//
StringBuffer sb2 = new StringBuffer();
StringBufferTest[] bufferThreads = new StringBufferTest[n];
for (int i = 0; i < n; i++) {
bufferThreads[i] = new StringBufferTest(sb2);
}
for (int i = 0; i < n; i++) {
bufferThreads[i].start();
}
for (int i = 0; i < n; i++) {
bufferThreads[i].join();
}
System.out.println("StringBufferTest: Expected result is 1000; got " + sb2.length());
}
}
// Every run would attempt to append 100 "A"s to the StringBuilder.
class StringBuilderTest extends Thread {
StringBuilder sb;
public StringBuilderTest (StringBuilder sb) {
this.sb = sb;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
sb.append("A");
}
}
}
//Every run would attempt to append 100 "A"s to the StringBuffer.
class StringBufferTest extends Thread {
StringBuffer sb2;
public StringBufferTest (StringBuffer sb2) {
this.sb2 = sb2;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
sb2.append("A");
}
}
}

- 2,307
- 26
- 31
Better use StringBuilder
since it is not synchronized and offers therefore better performance. StringBuilder
is a drop-in replacement of the older StringBuffer
.

- 21,519
- 75
- 241
- 416

- 1,306
- 5
- 15
- 28
-
3
-
3@Mark true but most of the time the `StringBu(ff|ild)er` is a local variable used only by a single thread. – gabuzo Jan 25 '11 at 12:25
-
1@MarkMcKenna: Even in a multi-threaded application, one would often either have to use external locking, or do extra work to avoid it. For example, if two threads each wish to append a record containing multiple strings to a stringbuilder, they would have to aggregate the data to be added and then add it as a unit even if it would have been faster--absent threading issues--to simply perform a sequence of discrete append operations. – supercat Mar 13 '14 at 15:54
StringBuffer
is synchronized, but StringBuilder
is not. As a result, StringBuilder
is faster than StringBuffer
.

- 30,199
- 37
- 136
- 151

- 59
- 1
StringBuffer is mutable. It can change in terms of length and content. 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 The StringBuilder class is very similar to StringBuffer, except that its 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.

- 224
- 1
- 6
StringBuffer:
- Multi-Thread
- Synchronized
- Slow than StringBuilder
StringBuilder
- Single-Thread
- Not-Synchronized
- Faster than ever String

- 3,658
- 4
- 44
- 80
-
2More precisely, `String c = a + b` is equivalent to `String c = new StringBuilder().append(a).append(b).toString()`, so it is not faster. It's only that you create a new one for each string assignation, while you could have only one (`String d = a + b; d = d + c;` is `String d = new StringBuilder().append(a).append(b).toString(); d = new StringBuilder().append(d).append(c).toString();` while `StringBuilder sb = new StringBuilder(); sb.append(a).append(b); sb.append(c); String d = sb.toString();` would save one StringBuilder instanciation). – Chop Oct 24 '15 at 16:50
String-Builder :
int one = 1;
String color = "red";
StringBuilder sb = new StringBuilder();
sb.append("One=").append(one).append(", Color=").append(color).append('\n');
System.out.print(sb);
// Prints "One=1, Colour=red" followed by an ASCII newline.
String-Buffer
StringBuffer sBuffer = new StringBuffer("test");
sBuffer.append(" String Buffer");
System.out.println(sBuffer);
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects.

- 2,093
- 4
- 28
- 41
-
If you need thread safety, the best option is to use StringBuilder as StringBuffer is only thread safe for individual operations. For multiple operations, you need explicit locking. – Peter Lawrey Jan 13 '19 at 10:34
A String
is an immutable object which means the value cannot be changed whereas StringBuffer
is mutable.
The StringBuffer
is Synchronized hence thread-safe whereas StringBuilder
is not and suitable for only single-threaded instances.

- 3,293
- 2
- 31
- 43

- 57
- 1
-
4just because StringBuffer has synchronized code, doesn't necessarily mean that StringBuffer is threadsafe. Consider the following example: StringBuffer testingBuffer = "stackoverflow"; Now Thread-1 is trying to append "1" to testingBuffer, and Thread-2 is trying to append "2" to testingBuffer. Now even though append() method is synchronized, u cannot be sure whether the value of testingBuffer will be "stackoverflow12" or "stackoverflow21". Actually, it is advised by Oracle to use stringbuilder over stringbuffer. I hope this helped :) – Biman Tripathy Dec 25 '12 at 21:29
-
@BimanTripathy's point above is actually an observation of multithreaded activity: with thread safety, we'll know that both "1" and "2" will get appended to "stackoverflow", but we don't know in what order. Without thread safety, "1" and "2" might both get appended, but we can also have one thread undoing the work made by the other, or both threads corrupting the internal state of the structure they used. – Luis May 14 '21 at 15:20
StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands as needed. Related classes: String, CharSequence.
StringBuilder was added in Java 5. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.
-
4Single-threaded programs are not the most common case in Java, but `StringBuilder`s are usually local to a method, where they are visible to only one thread. – finnw Jan 25 '11 at 14:36
Since StringBuffer
is synchronized, it needs some extra effort, hence based on perforamance, its a bit slow than StringBuilder
.

- 155
- 2
- 8

- 448
- 3
- 13
There are no basic differences between StringBuilder
and StringBuffer
, only a few differences exist between them. In StringBuffer
the methods are synchronized. This means that at a time only one thread can operate on them. If there is more than one thread then the second thread will have to wait for the first one to finish and the third one will have to wait for the first and second one to finish and so on. This makes the process very slow and hence the performance in the case of StringBuffer
is low.
On the other hand, StringBuilder
is not synchronized. This means that at a time multiple threads can operate on the same StringBuilder
object at the same time. This makes the process very fast and hence performance of StringBuilder
is high.

- 3,222
- 7
- 38
- 60

- 93
- 2
- 12
The major difference is StringBuffer
is syncronized but StringBuilder
is not.If you need to use more than one thread , then StringBuffer is recommended.But, as per the execution speed StringBuilder
is faster than StringBuffer
, because its not syncronized .

- 6,239
- 12
- 46
- 64
-
4StringBuffer is only thread safe if you perform just one operation on it. I wouldn't recommend using it in multiple thread because it is very hard to get right. Most uses of StringBuffer are not thread safe as they make multiple calls to it without external synchronization, making the class rather pointless. – Peter Lawrey Dec 17 '13 at 10:59
Check the internals of synchronized append method of StringBuffer
and non-synchronized append method of StringBuilder
.
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}
public synchronized StringBuffer append(Object obj) {
super.append(String.valueOf(obj));
return this;
}
public synchronized StringBuffer append(String str) {
super.append(str);
return this;
}
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
public StringBuilder append(Object obj) {
return append(String.valueOf(obj));
}
public StringBuilder append(String str) {
super.append(str);
return this;
}
Since append is synchronized
, StringBuffer
has performance overhead compared to StrinbBuilder
in multi-threading scenario. As long as you are not sharing buffer among multiple threads, use StringBuilder
, which is fast due to absence of synchronized
in append methods.

- 37,698
- 11
- 250
- 211
Here is the performance testing result for String vs StringBuffer vs StringBuilder. Finally, StringBuilder won the Test. See below for test code and result.
Code:
private static void performanceTestStringVsStringbuffereVsStringBuilder() {
// String vs StringBiffer vs StringBuilder performance Test
int loop = 100000;
long start = 0;
// String
String str = null;
start = System.currentTimeMillis();
for (int i = 1; i <= loop; i++) {
str += i + "test";
}
System.out.println("String - " + (System.currentTimeMillis() - start) + " ms");
// String buffer
StringBuffer sbuffer = new StringBuffer();
start = System.currentTimeMillis();
for (int i = 1; i <= loop; i++) {
sbuffer.append(i).append("test");
}
System.out.println("String Buffer - " + (System.currentTimeMillis() - start) + " ms");
// String builder
start = System.currentTimeMillis();
StringBuilder sbuilder = new StringBuilder();
for (int i = 1; i <= loop; i++) {
sbuffer.append(i).append("test");
}
System.out.println("String Builder - " + (System.currentTimeMillis() - start) + " ms");
}
Result:
100000 iteration for adding a single text
String - 37489 ms
String Buffer - 5 ms
String Builder - 4 ms
10000 iteration for adding a single text
String - 389 ms
String Buffer - 1 ms
String Builder - 1 ms

- 2,422
- 5
- 28
- 41
- StringBuffer is thread-safe but StringBuilder is not thread safe.
- StringBuilder is faster than StringBuffer.
- StringBuffer is synchronized whereas StringBuilder is not synchronized.

- 2,413
- 1
- 23
- 28
Every method present in StringBuffer is Synchronized. hence at a time only one thread is allowed to operate StringBuffer object. It Increases waiting time of a Thread and Creates Performance problems to overcome this problem SUN People intoduced StringBuilder in 1.5 version.

- 19
- 1
Others have rightly pointed out the key differences between the two. However in terms of performance I would like to add that a JVM level optimization "Lock Elision" which could make the performance difference in context of synchronization to be almost non-existent. An excellent read on this is here and here

- 8,874
- 2
- 28
- 37
StringBuilder is faster than StringBuffer because StringBuffer is synchronized, StringBuffer has its own char[] buffer for cache like BufferedInputStream does.
Another reason that StringBuffer is slower is that because every time you append or remove, it will update variable buffer. I tested it, and somehow StringBuffer‘s remove method is faster if I remove more than ten thousand times.