1744

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

0

33 Answers 33

1785

StringBuffer is synchronized, StringBuilder is not.

13
  • 252
    and StringBuilder is intended as a drop in replacement for StringBuffer where synchronisation is not required
    – Joel
    Dec 23, 2009 at 8:52
  • 100
    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, 2013 at 16:06
  • 25
    @locka I would argue that StringBuffer is never a good idea (unless you have an API which requires it) vanillajava.blogspot.de/2013/04/… Sep 4, 2013 at 10:21
  • 10
    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, 2014 at 16:10
  • 24
    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, 2016 at 17:50
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.

12
  • 13
    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). Aug 26, 2012 at 15:25
  • 12
    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.avrasm
    – mjs
    Nov 3, 2015 at 11:34
  • 86
    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? Dec 15, 2015 at 12:25
  • 27
    That i --> is really annoying syntax-wise... I thought it was an arrow at first because of the comments about ASCII art. Aug 10, 2016 at 19:14
  • 17
    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.
    – Lukas Eder
    Jun 2, 2017 at 9:03
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.

1
  • 2
    Also with Hashtable and HashMap.
    – shmosel
    Mar 17, 2017 at 19:14
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.

1
  • 16
    The first good answer!! The point is "unless you are sharing a buffer between threads"
    – AlexWien
    Mar 20, 2015 at 17:47
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.

1
  • 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, 2014 at 18:39
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.

2
  • 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. Sep 26, 2013 at 9:51
  • 1
    You should use JMH for benchmarks. Your benchmark is really inaccurate.
    – Lukas Eder
    Jun 2, 2017 at 9: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.

3
  • 13
    1.4 is at its End of Service Life, so it hardly seem worth worrying about pre-1.5. Dec 14, 2008 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. Mar 13, 2013 at 8:47
  • And CDC and CLDC don't have StringBuilder.
    – Jin Kwon
    Jul 12, 2013 at 3:47
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.

0
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
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. Jan 13, 2019 at 10:30
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

2
  • StringBuilder is immutable and String type is mutable Oct 15, 2018 at 11:37
  • I wouldn't agree that Strings and StringBuilders are "fast" and StringBuffers are "very slow". See the above answers.
    – kepe
    Feb 16, 2019 at 14:55
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.

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.

0
20

String is an immutable.

StringBuffer is a mutable and synchronized.

StringBuilder is also mutable but its not synchronized.

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...
    – Musa
    Feb 28, 2018 at 21:46
13

Difference between StringBuffer and StringBuilder Source:

enter image description here

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.

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.

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

    }
}
5

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

3
  • 3
    Unless your application is multithreaded, of course. :) Jan 25, 2011 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, 2011 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, 2014 at 15:54
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.

1
  • 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, 2011 at 14:36
4

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

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.

4

StringBuffer:

  • Multi-Thread
  • Synchronized
  • Slow than StringBuilder

StringBuilder

  • Single-Thread
  • Not-Synchronized
  • Faster than ever String
1
  • 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, 2015 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.

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. Jan 13, 2019 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.

2
  • 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 :) Dec 25, 2012 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, 2021 at 15:20
3

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

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.

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 .

1
  • 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. Dec 17, 2013 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.

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
1
  • StringBuffer is thread-safe but StringBuilder is not thread safe.
  • StringBuilder is faster than StringBuffer.
  • StringBuffer is synchronized whereas StringBuilder is not synchronized.

Not the answer you're looking for? Browse other questions tagged or ask your own question.