Sunday, August 14, 2011

StringBuilder vs StringBuffer

StringBuilder was introduced in JDK 1.5.

What's the difference between StringBuilder and StringBuffer?

According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage.

Their key differences in simple term:

StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.
StringBuilder has better performance than StringBuffer under most circumstances.
Use the new StringBuilder wherever possible.

String, StringBuffer and StringBuilder - use what?

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.

No comments:

Post a Comment