Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you use StringBuilder.AppendLine/string.Format vs. StringBuilder.AppendFormat?

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")); 
like image 739
Neil Barnwell Avatar asked Dec 08 '08 14:12

Neil Barnwell


People also ask

Is string format faster than StringBuilder?

StringBuilder is faster, because String. format has to parse the format string (a complex domain specific language).

What is AppendFormat?

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.

Why StringBuilder is used in C#?

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.

Is StringBuilder reference type?

The String object is immutable while StringBuilder object is mutable. Both String and StringBuilder are reference type.


1 Answers

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.

like image 115
Jon Skeet Avatar answered Oct 11 '22 21:10

Jon Skeet