A recent question came up about using String.Format(). Part of my answer included a suggestion to use StringBuilder.AppendLine(string.Format(...)). Jon Skeet suggested this was a bad example and proposed using a combination of AppendLine and AppendFormat.
It occurred to me I've never really settled myself into a "preferred" approach for using these methods. I think I might start using something like the following but am interested to know what other people use as a "best practice":
sbuilder.AppendFormat("{0} line", "First").AppendLine(); sbuilder.AppendFormat("{0} line", "Second").AppendLine(); // as opposed to: sbuilder.AppendLine( String.Format( "{0} line", "First")); sbuilder.AppendLine( String.Format( "{0} line", "Second"));
StringBuilder is faster, because String. format has to parse the format string (a complex domain specific language).
AppendFormat(IFormatProvider, String, Object) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a single argument using a specified format provider.
StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
The String object is immutable while StringBuilder object is mutable. Both String and StringBuilder are reference type.
I view AppendFormat
followed by AppendLine
as not only more readable, but also more performant than calling AppendLine(string.Format(...))
.
The latter creates a whole new string and then appends it wholesale into the existing builder. I'm not going to go as far as saying "Why bother using StringBuilder then?" but it does seem a bit against the spirit of StringBuilder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With