The String class is the most popular class in Java, especially in Web application development where it is used massively to format HTML output.
String is designed to be immutable. In order to modify a String, you have to create a new String object. Therefore, string concatenation can result in creating many intermediate String objects before the final String can be constructed.
StringBuffer is the mutable companion class of String. Therefore, StringBuffer is generally more efficient than String when concatenation is needed. Unfortunately it uses synchronized methods. If you are working in a multi-threaded application where you would have to worry about thread safety and synchronization, you should use StringBuffer (or Vector, or HashTable).
But if you are in a single threaded application, or one in which thread management is safely handled by an external resource, then the non-synchronized version is a better choice. StringBuilder is a relatively new addition to Java, introduced in JDK 1.5. According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage so StringBuilder has better performance than StringBuffer under most circumstances.
# Use the new StringBuilder wherever possible!!!
String is designed to be immutable. In order to modify a String, you have to create a new String object. Therefore, string concatenation can result in creating many intermediate String objects before the final String can be constructed.
StringBuffer is the mutable companion class of String. Therefore, StringBuffer is generally more efficient than String when concatenation is needed. Unfortunately it uses synchronized methods. If you are working in a multi-threaded application where you would have to worry about thread safety and synchronization, you should use StringBuffer (or Vector, or HashTable).
But if you are in a single threaded application, or one in which thread management is safely handled by an external resource, then the non-synchronized version is a better choice. StringBuilder is a relatively new addition to Java, introduced in JDK 1.5. According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage so StringBuilder has better performance than StringBuffer under most circumstances.
# Use the new StringBuilder wherever possible!!!
Komentáre