What is the difference between String and StringBuffer in Java?

String is used to manipulate character strings that cannot be changed (read-only and immutable). StringBuffer is used to represent characters that can be modified. Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable. You can … Read more

Is String.Format as efficient as StringBuilder

NOTE: This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions. String.Format uses a StringBuilder internally: public static string Format(IFormatProvider provider, string format, params object[] args) { if ((format == null) || (args == null)) { throw new ArgumentNullException((format == null) ? “format” : “args”); } … Read more

Java: String concat vs StringBuilder – optimised, so what should I do?

I think the use of StringBuilder vs + really depends on the context you are using it in. Generally using JDK 1.6 and above the compiler will automatically join strings together using StringBuilder. String one = “abc”; String two = “xyz”; String three = one + two; This will compile String three as: String three … Read more

How can I clear or empty a StringBuilder? [duplicate]

Two ways that work: Use stringBuilderObj.setLength(0). Allocate a new one with new StringBuilder() instead of clearing the buffer. Note that for performance-critical code paths, this approach can be significantly slower than the setLength-based approach (since a new object with a new buffer needs to be allocated, the old object becomes eligible for GC etc).

How the StringBuilder class is implemented? Does it internally create new string objects each time we append?

In .NET 2.0 it uses the String class internally. String is only immutable outside of the System namespace, so StringBuilder can do that. In .NET 4.0 String was changed to use char[]. In 2.0 StringBuilder looked like this public sealed class StringBuilder : ISerializable { // Fields private const string CapacityField = “Capacity”; internal const … Read more

When to use StringBuilder?

I warmly suggest you to read The Sad Tragedy of Micro-Optimization Theater, by Jeff Atwood. It treats Simple Concatenation vs. StringBuilder vs. other methods. Now, if you want to see some numbers and graphs, follow the link 😉