What is the main difference between StringBuffer
and StringBuilder
? Is there any performance issues when deciding on any one of these?
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.
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.
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.
StringBuffer
is synchronized, StringBuilder
is not.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With