Difference between StringBuilder and StringBuffer
Asked Answered
R

33

1744

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

Rowney answered 10/12, 2008 at 4:34 Comment(0)
D
1785

StringBuffer is synchronized, StringBuilder is not.

Diageotropism answered 10/12, 2008 at 4:36 Comment(13)
and StringBuilder is intended as a drop in replacement for StringBuffer where synchronisation is not requiredTheophany
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 instanceMaishamaisie
@Maishamaisie I would argue that StringBuffer is never a good idea (unless you have an API which requires it) vanillajava.blogspot.de/2013/04/…Sachikosachs
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.Calathus
javahungry.blogspot.com/2013/06/…Levey
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.Hobard
But StringBuffer is slower than StringBuilder. You choose the one you perfer based on what kind of applications you work onNobile
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.Fanning
java.lang.StringBuffer : All methods except the Constructor are synchronized Vs java.lang.StringBuilder : All of them are normal (non-synchronized) methodsNonrigid
To find more details about What actual cause the StringBuilder fails in multi threading environment I have asked a question that could be helpful #31376218Samy
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.Contingency
@D.Everhard Agreed, actually I also got confused. This should be corrected.Hoogh
@Diageotropism StringBuilder is not immutable, shocked as no one pointed outHatshepsut
U
762

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.

Uppercase answered 5/5, 2010 at 9:15 Comment(12)
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).Hussar
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)Fledgling
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 hastebin.com/piwicifami.avrasmLiebermann
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.Liebermann
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?Contingency
Yeah Even i have not used such for constructs --> 0 , I tried using {for (int i = 0; i --> N ;)} which did not work ? .Microelement
That i --> is really annoying syntax-wise... I thought it was an arrow at first because of the comments about ASCII art.Measureless
@D.Everhard and the others: This may be an interesting read to you.Acquisitive
Others conclude with different results: 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.Goalkeeper
what a nice world it would be if for (int i = N; i --> 0 ;) counted as a party trickLariat
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 itCretin
@SameerPuri thank you (from much later). Lol I thought the same thing. My brain segfaulted for 5 seconds, then in crisis I googled "Java \"-->\" operator" and confirmed the guess, that it means "--" and ">"Madness
B
269

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.

Bell answered 10/12, 2008 at 4:37 Comment(1)
Also with Hashtable and HashMap.Flop
S
197

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.

Spurn answered 25/1, 2011 at 12:30 Comment(1)
The first good answer!! The point is "unless you are sharing a buffer between threads"Amalita
W
88

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.

Wrench answered 11/12, 2013 at 7:11 Comment(1)
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!Psychotic
H
59

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.

Hut answered 15/11, 2012 at 16:20 Comment(2)
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.Quadroon
You should use JMH for benchmarks. Your benchmark is really inaccurate.Goalkeeper
E
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.

Eire answered 10/12, 2008 at 4:38 Comment(3)
1.4 is at its End of Service Life, so it hardly seem worth worrying about pre-1.5.Purgation
@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.Viscoid
And CDC and CLDC don't have StringBuilder.Annmaria
N
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.

Nonagenarian answered 11/4, 2014 at 20:25 Comment(0)
K
27

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
Krohn answered 10/12, 2008 at 5:0 Comment(1)
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.Sachikosachs
C
25

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

Congenial answered 20/9, 2016 at 17:40 Comment(2)
StringBuilder is immutable and String type is mutableUnhair
I wouldn't agree that Strings and StringBuilders are "fast" and StringBuffers are "very slow". See the above answers.Klockau
P
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.

Postaxial answered 10/12, 2008 at 4:41 Comment(0)
B
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.

Beanery answered 3/12, 2010 at 6:38 Comment(0)
T
20

String is an immutable.

StringBuffer is a mutable and synchronized.

StringBuilder is also mutable but its not synchronized.

Tricyclic answered 18/3, 2013 at 8:12 Comment(1)
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...Amitosis
M
13

Difference between StringBuffer and StringBuilder Source:

enter image description here

Maiocco answered 3/7, 2020 at 6:41 Comment(0)
K
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.

Kg answered 25/1, 2011 at 12:21 Comment(0)
C
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.

Charbonnier answered 25/1, 2011 at 12:23 Comment(0)
P
7

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

    }
}
Psychotic answered 14/3, 2014 at 18:40 Comment(0)
I
5

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

Issuance answered 25/1, 2011 at 12:21 Comment(3)
Unless your application is multithreaded, of course. :)Boutique
@Mark true but most of the time the StringBu(ff|ild)er is a local variable used only by a single thread.Heterodox
@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.Gibson
L
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.

Lexicography answered 23/4, 2009 at 13:44 Comment(1)
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.Oldwife
P
4

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

Pinero answered 23/12, 2009 at 8:42 Comment(0)
A
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.

Apus answered 17/11, 2010 at 11:33 Comment(2)
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 :)Phyllode
@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.Lathan
R
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.

Reactive answered 5/9, 2014 at 10:2 Comment(0)
M
4

StringBuffer:

  • Multi-Thread
  • Synchronized
  • Slow than StringBuilder

StringBuilder

  • Single-Thread
  • Not-Synchronized
  • Faster than ever String
Mopes answered 27/9, 2015 at 20:34 Comment(1)
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).Stupefaction
T
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.

Trover answered 1/2, 2017 at 8:44 Comment(1)
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.Sachikosachs
S
3

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

Suzannasuzanne answered 25/7, 2013 at 6:39 Comment(0)
G
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.

Griseldagriseldis answered 10/5, 2016 at 7:57 Comment(0)
M
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 .

Mahatma answered 15/11, 2013 at 18:5 Comment(1)
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.Sachikosachs
S
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.

Surratt answered 9/6, 2016 at 7:16 Comment(0)
G
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
Gallbladder answered 24/8, 2018 at 7:59 Comment(0)
A
1
  • StringBuffer is thread-safe but StringBuilder is not thread safe.
  • StringBuilder is faster than StringBuffer.
  • StringBuffer is synchronized whereas StringBuilder is not synchronized.
Advice answered 1/11, 2018 at 17:41 Comment(0)
E
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.

Eaglewood answered 1/7, 2013 at 13:52 Comment(0)
B
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

Bis answered 19/10, 2019 at 9:1 Comment(0)
R
0

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.

Reims answered 17/4, 2022 at 12:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.