1638

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

Raedwald
  • 40,290
  • 35
  • 127
  • 207
blacktiger
  • 18,007
  • 5
  • 18
  • 11

32 Answers32

1716

StringBuffer is synchronized, StringBuilder is not.

Raimund Krämer
  • 1,095
  • 9
  • 27
sblundy
  • 58,164
  • 22
  • 117
  • 120
  • 244
    and StringBuilder is intended as a drop in replacement for StringBuffer where synchronisation is not required – Joel Dec 23 '09 at 08:52
  • 98
    and 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
  • 9
    Only 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
  • 22
    Good 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
  • 3
    Another 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
  • 1
    Why 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
  • StringBuffer is faster in execution than StringBuilder. – N.Chandimali Mar 11 '18 at 18:33
739

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.

ACV
  • 8,090
  • 4
  • 56
  • 72
polygenelubricants
  • 348,637
  • 121
  • 546
  • 611
  • 11
    I 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
  • 8
    You 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 – mmm 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. – mmm Nov 03 '15 at 11:47
  • 80
    This 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
  • 1
    Yeah 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
  • 24
    That `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
  • 16
    Others 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
  • 2
    what 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
253

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.

Ashish Kumar
  • 816
  • 2
  • 14
  • 31
OscarRyz
  • 184,433
  • 106
  • 369
  • 548
182

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.

Community
  • 1
  • 1
Bert F
  • 78,021
  • 11
  • 97
  • 121
82

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.

archity
  • 416
  • 1
  • 6
  • 18
user1923551
  • 4,396
  • 32
  • 28
  • 2
    Just 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
58

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.

Nicolas Zozol
  • 6,609
  • 1
  • 46
  • 66
  • 6
    You 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
  • 1
    You should use JMH for benchmarks. Your benchmark is really inaccurate. – Lukas Eder Jun 02 '17 at 09:21
42

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.

MrTux
  • 28,370
  • 24
  • 91
  • 123
Marc Novakowski
  • 42,180
  • 11
  • 55
  • 62
37

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.

Sireesh Yarlagadda
  • 10,572
  • 2
  • 65
  • 71
24

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
AJPerez
  • 3,039
  • 8
  • 59
  • 82
JRomio
  • 1,937
  • 2
  • 19
  • 26
  • 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
23

StringBuilder is not thread safe. String Buffer is. More info here.

EDIT: As for performance , after hotspot kicks in , StringBuilder is the winner. However , for small iterations , the performance difference is negligible.

Learning
  • 7,553
  • 3
  • 29
  • 45
21

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.

Nikolai Samteladze
  • 7,337
  • 4
  • 41
  • 70
subodh ray
  • 221
  • 3
  • 6
20

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

enter image description here

Resource: String Vs StringBuffer Vs StringBuilder

Affy
  • 2,425
  • 22
  • 32
18

String is an immutable.

StringBuffer is a mutable and synchronized.

StringBuilder is also mutable but its not synchronized.

Ani Menon
  • 23,084
  • 13
  • 81
  • 107
sudhakar
  • 217
  • 2
  • 2
  • 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
11

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.

skaffman
  • 381,978
  • 94
  • 789
  • 754
10

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.

1ac0
  • 2,695
  • 2
  • 29
  • 46
Sébastien Le Callonnec
  • 23,877
  • 6
  • 58
  • 77
6

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");
        }

    }
}
Kevin Lee
  • 2,087
  • 22
  • 29
4

StringBuffer is synchronized, but StringBuilder is not. As a result, StringBuilder is faster than StringBuffer.

Pops
  • 28,257
  • 34
  • 127
  • 149
4

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.

Android Genius
  • 214
  • 1
  • 6
4

StringBuffer:

  • Multi-Thread
  • Synchronized
  • Slow than StringBuilder

StringBuilder

  • Single-Thread
  • Not-Synchronized
  • Faster than ever String
Asif Mushtaq
  • 3,020
  • 2
  • 34
  • 64
  • 2
    More 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
4

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.

Avinash
  • 1,739
  • 2
  • 19
  • 40
  • 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
4

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.

Rahul
  • 2,374
  • 2
  • 22
  • 36
  • 4
    just 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
4

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

Alexander Farber
  • 18,345
  • 68
  • 208
  • 375
Niclas
  • 1,266
  • 3
  • 14
  • 27
  • 3
    Unless your application is multithreaded, of course. :) – Mark McKenna Jan 25 '11 at 12:23
  • 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
4

Difference between StringBuffer and StringBuilder Source:

enter image description here

Zohra Khan
  • 4,674
  • 3
  • 22
  • 32
4

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.

  • 4
    Single-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
3

Since StringBuffer is synchronized, it needs some extra effort, hence based on perforamance, its a bit slow than StringBuilder.

L Joey
  • 125
  • 2
  • 7
Shuhail Kadavath
  • 448
  • 3
  • 13
3

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.

ThisaruG
  • 2,382
  • 5
  • 34
  • 50
Pratik Paul
  • 83
  • 1
  • 10
2

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 .

JDGuide
  • 5,759
  • 11
  • 39
  • 53
  • 4
    StringBuffer 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
2

Check the internals of synchronized append method of StringBuffer and non-synchronized append method of StringBuilder.

StringBuffer:

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;
}

StringBuilder:

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.

Ravindra babu
  • 42,401
  • 8
  • 208
  • 194
1

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");

  }

Execute Me on ideone

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
Ganesa Vijayakumar
  • 1,942
  • 5
  • 21
  • 36
1
  • StringBuffer is thread-safe but StringBuilder is not thread safe.
  • StringBuilder is faster than StringBuffer.
  • StringBuffer is synchronized whereas StringBuilder is not synchronized.
Praveen Kishor
  • 1,713
  • 1
  • 18
  • 19
0

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.

Srinivas
  • 19
  • 1
0

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

Shailendra
  • 6,814
  • 2
  • 21
  • 32