We will see the differences between String, StringBuffer and StringBuilder.
The main differences are related to thread safe nature and performance.
Difference String StringBuffer and StringBuilder
String
1. String is immutable – So string is Thread Safe.
2. Any operations on String, like concat can take more time in comparison with StringBuffer and StringBuilder.
3. If you are going to use static text/constants or if your data is not going to change between 2 threads – then use String.
StringBuffer
1. StringBuffer is mutable but all methods of StringBuffer are synchronized, So StringBuffer is Thread Safe.
2. But ThreadSafe impacts the performance, StringBuffer is less efficient in terms of performance.
3. If you are going to change the data which will be used by multiple threads then only use StringBuffer.
StringBuilder
1. StringBuilder is mutable and not synchronized, So StringBuilder is not Thread Safe.
2. But StringBuilder is more efficient than StringBuffer or String when it comes to performing any operations or data manipulations.
3. If you are going to change the data which will be used by only one thread at a time then only use StringBuilder.
For single threaded applications use StringBuilder instead of StringBuffer or Strings for data related operations.
Lets see a example that will show the difference in performance for String StringBuffer and StringBuilder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com.kscodes.sampleproject; public class StringPerformance { public static void main(String[] args) { String str1 = "Performance"; // Add 100000 Strings in String long startTime1 = System.currentTimeMillis(); String testStr = ""; for (int i = 0; i < 100000; i++) { testStr = testStr + str1; } long endTime1 = System.currentTimeMillis(); System.out.println("Time required to Add 100000 Strings in String (ms) ::" + (endTime1 - startTime1)); // Add 100000 Strings in StringBuffer long startTime2 = System.currentTimeMillis(); StringBuffer testStrBuffer = new StringBuffer(); for (int i = 0; i < 100000; i++) { testStrBuffer.append(str1); } long endTime2 = System.currentTimeMillis(); System.out .println("Time required to Add 100000 Strings in StringBuffer (ms) ::" + (endTime2 - startTime2)); // Add 100000 Strings in StringBuilder long startTime3 = System.currentTimeMillis(); StringBuilder testStrBuilder = new StringBuilder(); for (int i = 0; i < 100000; i++) { testStrBuilder.append(str1); } long endTime3 = System.currentTimeMillis(); System.out .println("Time required to Add 100000 Strings in StringBuilder (ms) ::" + (endTime3 - startTime3)); } } |
Output
1 2 3 |
Time required to Add 100000 Strings in String (ms) ::57567 Time required to Add 100000 Strings in StringBuffer (ms) ::28 Time required to Add 100000 Strings in StringBuilder (ms) ::13 |