views:

300

answers:

8

Possible Duplicate:
How should I concatenate strings?

There are several ways to concat strings in everyday tasks when performance is not important.

  • result = a + ":" + b
  • result = string.Concat(a, ":", c)
  • result = string.Format("{0}:{1}", a, b);
  • StringBuilder approach
  • ... ?

what do you prefer and why if efficiency doesn't matter but you want to keep the code most readable for your taste?

+6  A: 

string.Format for me, but in practice I use whichever is fit for purpose, taking into account performance and readability.

If it was two variables I'd use.

string.Concat(str1, str2);

If it contained a constant or something that requires formatting then.

string.Format("{0} + {1} = {2}", x, y, x + y);

Or for something like an SQL query

string SqlQuery = "SELECT col1, col2, col3, col4" + 
                  "FROM table t " + 
                  "WHERE col1 = 1";

And string builder when performance matters.

Chris Diver
Premature optimization is the root of all evil. Or something like that.
strager
+1 for readability's sake.
p.campbell
+1 for the method. I've even created a short cut i use it so often
gnome
I'd prefer using multi-line strings instead of concatenating multiple strings by using the @ sign.
Steven
+1  A: 

String.Format(...) is slowest.

For simple concatenations which don't take place in a loop, use String.Concat(...) or the + operator, which translate to the same under the hood, afaik. What is more readable is very subjective.

Using a StringBuilder for simple concatenations is over-the-top for simple concatenations as well and has most likely too much overhead. I'd only use it in a loop.

herzmeister der welten
Thank you, but how do you ordinary concatenate strings? Format, +, Concat ?
Andrew Florko
I wouldn't make my decision solely based on PERFORMANCE, unless performance is absolutely critical and it was PROVEN that a particular String.Format call was to blame for serious performance problems. You should generally prefer readability and maintainability to performance. That having been said, I have no problem with this answer as it's factual, but it just strikes me that the implication is that performance is king, and in reality it should be your last consideration given that the difference in speed is measured in fractions of miliseconds.
mattmc3
The most 'ordinary' way is to use `+` or `Concat`, which translate to the same under the hood afaik, and which you find more readable is very subjective. I wouldn't use `String.Format(...)` for simple things because it is slower (has to parse the format string) and is more error prone.
herzmeister der welten
+1  A: 
  • string.Format

    for few concats. for more I use

  • StringBuilder approach

even if performance is not important. there is a team agreement I have to follow

Arseny
Thanks, we do just the same. Though some developers tends to use +
Andrew Florko
+2  A: 

For something like this (which I'm guessing is being sent to the UI), I would definitely prefer String.Format. It allows the string to be internationalized easy; you can grep for calls to String.Format and replace them with your translating format.

strager
+1 for the point on localization.
Chris Taylor
+1  A: 

My personal preference is:

I find the + approach the most readable and only use Format() or a StringBuilder if there is a good reason (i18n, performance etc) for it. I (almost) never use Concat.

I think I find the + approach easier to read than Format() simply because I don't have to skip ahead to the end to see what variables are put into in the {} place-holders. And if the place-holders aren't in numeric order, it gets even harder to read imo.

But I guess for larger projects it makes sense to simply enforce using Format by a style guide just in case the code might be (re-)used in a project requiring i18n later on.

Ben Schwehn
+7  A: 

It depends on the use. When you just want to concat two strings, using a + b is just much more readable than string.Format("{0}{1}", a, b). However, it is getting more complex, I prefer using string.Format. Compare this:

string x = string.Format("-{0}- ({1})", a, b);

against:

string x = "-" + a + "- (" + b + ")";

I think that in most cases it is very easy to spot the most readable way to do things. In the cases where it is debatable which one is more readable, just pick one, because your boss isn't paying for these pointless discussions ;-)

Steven
+1 for the last sentence. :) Most of the time it really doesn't matter; you could be doing something more productive than deciding which string concatenation method to use.
musicfreak
Agreed, but it's hard to measure the time spent re-learning what you or someone else did when you have to maintain that code. Often the few extra seconds spent making something easier to read and understand will save you later when you aren't already fully into the problem and have to fix something. So you want to write understandable code and develop good habits. Maintenance is one of the biggest costs to your developers, and is something your boss should definitely be concerned about.
mattmc3
@mattmc: DGMW: I think maintainability is (after correctness) the most important aspects of software. I’ve seen lots of poor code in my career that became a maintenance nightmare. Discussing it with your colleges is important to get a general consensus about what is most readable. However, there’s always a trade-off between that and productivity. As you said, it’s hard to measure where the break-even point lies.Having these discussions is useful up to a point. What I tried to say was that having endless discussions about several flavors that are just too close in readability isn’t very useful.
Steven
+1  A: 

I prefer String.Format for small strings, and StringBuilder for larger ones. My main reason is readability. It's a lot more readable to me to use String.Format (or StringBuilder.AppendFormat()), but I have to admit that that is just personal preference.

For really big text generation, you might want to consider using the new (VS2010) T4 Preprocessed Templates - they are really nice.

Also, if you're ever in VB.NET, I like the XML literal technique Kathleen Dollard talked about in episode 152 of hanselminutes.

mattmc3
Also note that `string.Format` uses a `StringBuilder` internally.
Steven
+1  A: 

Prefer to use:

String.Concat for simple concatenations like String.Concat("foo", bar);

String.Format for complex formatting like String.Format("<a href=\"{0}\">{1}</a>", url, text);

StringBuilder for massive concatenations like:

var sb = new StringBuilder();
sb.AppendLine("function fooBar() {");
sp.AppendLine(String.Join(Environment.NewLine, blah));
sp.AppendLine("}");
page.RegisterClientScript(page.GetType(), sb.ToString());

Prefer to avoid "foo" + "bar" (as well as if (foo == "bar"). And especially String.Format("{0}{1}", foo, bar) and

throw new Exception("This code was" +
    "written by developer with" +
    "13\" monitor");
abatishchev