views:

209

answers:

7

In my early .Net programming days, I used string.Format() only for complex string concatenations, for example to compile strings as

Problem with customer order 234 of date 2/2/2002 and payment id 55543.

But now I use string.Format for almost every string concatenation I have to do, also simple ones such as prefixing a string with something.

Console.WriteLine(string.Format("\t\t{0}", myString));

Is there any possible overhead on this? Maybe I should use the regular + operator to do these simple operations?

What's your opinion on this?

+2  A: 
Justin Niessner
+1 for the tip, I didn't know that :)
Gerrie Schenck
You are way off about the performance of a `StringBuilder`. The `StringBuilder` is **much** less efficient than string concatenation in both your examples and you *really* shouldn’t use it as a substitute for such things as `a + b`. It’s big, ugly and inefficient.
Konrad Rudolph
@Konrad - Indeed. I am quite off the mark. A quick look at Jon Skeet's blog clears things up nicely: http://www.yoda.arachsys.com/csharp/stringbuilder.html
Justin Niessner
+5  A: 

For simple string concatenations use the + approach. It is clearer for simple things that don't require a format.

For more complex strings that have a certain format and where it is useful to retain the structure of the entire string and provide a placeholder for the input, use String.Format.

And yes, there is an overhead. String.Format uses a StringBuilder underneath the covers. Simple string concatenations will be much quicker in those scenarios. A couple of benchmarks and blog posts on this topic can be found quite easily. Of course it all depends on your usage. If small string concats are occurring in a loop then repeated usage of String.Format will likely be more noticeable than a straightforward + concat. If you are building up a large string in a loop then the classic example is to prefer StringBuilder and related questions on concat versus StringBuilder can be found on SO.

EDIT: To clarify, this serves little purpose: String.Format("{0}{1}", a, b) since there is not much formatting. It's simply a + b. Unfortunately I've come across such examples in production code and as soon as I see String.Format I expect to see something that needs to be structured a certain way, not a straightforward concat.

OTOH, consider this phone number: "(" + area + ") " + number + " x" + extension - there's too much going on and it's not easy to modify. In this case a String.Format is preferable: String.Format("({0}) {1} x{2}", area, number, extension). This is still a trivial example but you get the idea.

Ahmad Mageed
string.Format also has to parse the format string to start with...
Jon Skeet
This kind of code should only ever be used in an I/O operation. I/O is always expensive, especially Console.WriteLine(). The cost of parsing a composite formatting string is negligible, optimizing it is pointless.
Hans Passant
A: 

I don't know about performance, someone will likely provide that data, but my feeling is that String.Format is the way to go if you want to put the format string in your config file (or database field or resource file or whatever). That way, if you want to tweak the number of tabs, switch to spaces, add delimiters, or whatever, you don't have to recompile.

brianary
+2  A: 

I also tend to use string.Format on most operation which need two or more strings/values to be combined as it produces easier to read code than starting and stopping strings with +'s in the middle.

To expand

string value = string.Format("Hello {0}", user.username);

is much more readable and expandable than

string value = "Hello" + user.username

for instance if you wanted to add the last login date as a system upgrade, you could simply expand the code to the following

string value = string.Format("Hello {0}, you last logged in {1}", user.username, user.lastLogin);
GaryDevenay
A: 

I tend to use String.Concat instead of String.Format when I just need to prefix or suffix a given string. I prefer the explicit call to the Concatmethod then to use the + operator and if you are already use String.Format it's just a matter of switching one keystroke.

IIRC, the String.Concat method will be the same as using the operator so it also be faster than String.Format.

João Angelo
+1  A: 

My rule is if I have to use the + (concatenation) more than once I change it to a string.Format.

string a = "Something: " + x;   // ok

string b = "Something: " + x + " something else"; // change it to a string.Format
string bB = string.Format("Something: {0} something else", x); // much nicer to read

string c = "Something: " + x + " " + y + " " + z;  // Yuck
string cC = string.Format("Something: {0} {1} {2}", x, y, x);  // Much nicer
Kelsey
A: 

I almost always use format, although I use an extension method instead of the static string method. I find it easier to understand, easier to change, and generally easier to maintain. It can also make localization easier because it doesn't introduce ordering issues the way concatenation does.

Honestly, which looks better?

"You have {0} widgets.".Frmt(widgetCount)
"You have " + widgetCount.ToString() + " widgets."
Strilanc