Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between StringBuilder and StringBuffer

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

like image 451
blacktiger Avatar asked Dec 10 '08 04:12

blacktiger


People also ask

What is difference between String and StringBuffer?

In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. Whereas, StringBuffer class is a thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.

Why do we use StringBuffer and StringBuilder in Java?

The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters. Unlike Strings, objects of type StringBuffer and String builder can be modified over and over again without leaving behind a lot of new unused objects.

Why StringBuffer is slower than StringBuilder?

StringBuffer is a mutable and synchronized. StringBuilder is also mutable but its not synchronized. Additionally StringBuffer locks Threads for access this thread safe data that's why operation goes slowly. StringBuilder does not lock thread and it runs in Multi Threading way that's why is fast.


2 Answers

StringBuffer is synchronized, StringBuilder is not.

like image 70
sblundy Avatar answered Oct 06 '22 00:10

sblundy


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.

like image 39
polygenelubricants Avatar answered Oct 06 '22 00:10

polygenelubricants