We know Strings are immutable, so each time a string is changed, a new instance in memory is created.
But StringBuffer and StringBuilder can change their values.
The only difference between StringBuffer and StringBuilder is:
StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer for single threaded operations.
Criteria to choose among String, StringBuffer and StringBuilder:
- If your text is not going to change use a string Class because a String object is immutable.
- If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
- If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.
Some Test Results:
For 1000000 String Concatination:
StringBuffer elapsed time in milliseconds: 348 , 314 , 320 , 311
StringBuilder elapsed time in milliseconds: 220 , 226 , 225 , 245
But for String for 10000 String concatination: It took 4471 , 4384 milliseconds. Bcs On the ( + ) operation a new String object is created at each iteration