String output: format or concat in C#?
Asked Answered
T

32

184

Let's say that you want to output or concat strings. Which of the following styles do you prefer?

  • var p = new { FirstName = "Bill", LastName = "Gates" };

  • Console.WriteLine("{0} {1}", p.FirstName, p.LastName);

  • Console.WriteLine(p.FirstName + " " + p.LastName);

Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes?

Do you have any rational arguments to use one and not the other?

I'd go for the second one.

Thumping answered 19/8, 2008 at 15:47 Comment(0)
Q
89

Try this code.

It's a slightly modified version of your code.

  1. I removed Console.WriteLine as it's probably a few orders of magnitude slower than what I'm trying to measure.
  2. I'm starting the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute.
  3. The way you divided the result by some iterations was wrong. See what happens if you have 1,000 milliseconds and 100 milliseconds. In both situations, you will get 0 ms after dividing it by 1,000,000.

Code:

Stopwatch s = new Stopwatch();

var p = new { FirstName = "Bill", LastName = "Gates" };

int n = 1000000;
long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;

string result;
s.Start();
for (var i = 0; i < n; i++)
    result = (p.FirstName + " " + p.LastName);
s.Stop();
cElapsedMilliseconds = s.ElapsedMilliseconds;
cElapsedTicks = s.ElapsedTicks;
s.Reset();
s.Start();
for (var i = 0; i < n; i++)
    result = string.Format("{0} {1}", p.FirstName, p.LastName);
s.Stop();
fElapsedMilliseconds = s.ElapsedMilliseconds;
fElapsedTicks = s.ElapsedTicks;
s.Reset();


Console.Clear();
Console.WriteLine(n.ToString()+" x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");
Console.WriteLine(n.ToString() + " x result = (p.FirstName + \" \" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");
Thread.Sleep(4000);

Those are my results:

1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 618ms - 2213706 ticks
1000000 x result = (p.FirstName + " " + p.LastName); took: 166ms - 595610 ticks

Quinquefid answered 19/8, 2008 at 15:47 Comment(4)
Very interesting. I got an average of 224ms vs. 48ms, an x4.66 improvement, even better than your x3.72. I wonder if there is a post-compilation tool that can rewrite the IL of string.Format that doesn't use any composite formatting features (i.e. just simple {0}) and replace them with the considerably faster string concatenation. I wonder such a feat is achievable with an existing IL rewriter such as PostSharp.Confabulate
Strings are immutable, this means the same tiny piece of memory is used over and over in your code. Adding the same two strings together and creating the same new string over and over again doesn't impact memory. .Net is smart enough just to use the same memory reference. Therefore your code doesn't truly test the difference between the two concat methods. See code in my answer below.Stoeber
Honestly, I always concatenate since it's easier to read for me and wow it's faster :)Cookhouse
So speed is the only reason to choose one over the other?Subsist
E
162

I'm amazed that so many people immediately want to find the code that executes the fastest. If ONE MILLION iterations STILL take less than a second to process, is this going to be in ANY WAY noticeable to the end user? Not very likely.

Premature optimization = FAIL.

I'd go with the String.Format option, only because it makes the most sense from an architectural standpoint. I don't care about the performance until it becomes an issue (and if it did, I'd ask myself: Do I need to concatenate a million names at once? Surely they won't all fit on the screen...)

Consider if your customer later wants to change it so that they can configure whether to display "Firstname Lastname" or "Lastname, Firstname." With the Format option, this is easy - just swap out the format string. With the concat, you'll need extra code. Sure that doesn't sound like a big deal in this particular example but extrapolate.

Evacuate answered 19/8, 2008 at 15:47 Comment(12)
Good point in terms of "Premature Optimisation == FAIL", yes. But, when you start paying for execution footprint (cloud and infrastructure as a service, anyone?) and/or you start supporting 1 million users on something then the response to a single user on a request is not the question. The cost of servicing a request to a user is a cost to your bottom line as well as a scale issue if/when several other thousand calls are coming through ...Contuse
This is just totally wrong. In a web development environment, often times your string generation code will be deep in both your model, views and controllers and can get called tens of thousands of times per page load. Reducing the length of time spend evaluating string generation code by 50% could be an enormous win.Godoy
I agree on Premature optimization = FAIL. However there is an uncertain threshold between doing the work well and premature optimization. To explain my idea, if somebody is planning to process 2 billions of lines then, every millisecond is important. But on the other hand if it's just to print a message that barely is going to be used then it's not work to invest time on deciding.Stratum
A question like this isn't just going to apply in the OP's one instance. THe answer is the kind of thing that people can remember as "which way should I assemble strings?" as they write all of their code.Slicker
@Benjamin: ...in which case, you'd profile and find that to be your bottleneck. I would bet money that you are just pulling that from nowhere, though; having written and profiled a number of webapps in the past, I've almost always found the bottleneck in response times (on the serverside) to be the database queries.Putt
@BlueRaja-DannyPflughoeft definitely not pulling it out of nowhere. A super-fast website will not have DB queries block http web requests from users and instead will read from in-memory caches. Read highscalability.comGodoy
This is most definitely NOT premature optimization. Quite the fallacy. String performance can completely stall up UIs, especially in .NET if you're doing a lot of formatting and String building. ubiquity.acm.org/article.cfm?id=1513451Enloe
I would have agreed with you if i hadn't had to deal with a performance problem directly related to using string.format(). dealing with a data heavy line of business application that used lots of string.format() calls because it was easy, but when dealing with 1000+ concurrent users 20 string.format calls on a page added up quickYeisk
@FredrikKalseth "Best practice" is not equal to "premature optimisation". Finding the best approach for something to make it a habit can save countless hours/days and even weeks of after-the-fact troubleshooting and optimisation. This is simple enough to adopt as a "best practice" without overthinking it. But, I agree with your fair warning / sentiment that "premature optimisation = fail".Languedoc
There is no such thing as "premature optimization".... Code is either optimized for the task at hand or it is not... It is simply a prejudice. You are just repeating around what you heard or read online. As matter of fact in my opinion the motto "premature optimization" has become an excuse for writing crappy code.Rudderhead
@Contuse True performance is a factor - but the architectural reasons for the choice weren't even touched on in previous answers - they must at least be taken into account.Subsist
@Contuse if you have one million users on your cloud platform, I'm hoping you also have the revenue stream to pay for those few nanoseconds per user. If not, I'd consider it a failed business model. The cost per request or cost per user here is the only thing that matters.Anthropomorphize
Q
89

Try this code.

It's a slightly modified version of your code.

  1. I removed Console.WriteLine as it's probably a few orders of magnitude slower than what I'm trying to measure.
  2. I'm starting the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute.
  3. The way you divided the result by some iterations was wrong. See what happens if you have 1,000 milliseconds and 100 milliseconds. In both situations, you will get 0 ms after dividing it by 1,000,000.

Code:

Stopwatch s = new Stopwatch();

var p = new { FirstName = "Bill", LastName = "Gates" };

int n = 1000000;
long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;

string result;
s.Start();
for (var i = 0; i < n; i++)
    result = (p.FirstName + " " + p.LastName);
s.Stop();
cElapsedMilliseconds = s.ElapsedMilliseconds;
cElapsedTicks = s.ElapsedTicks;
s.Reset();
s.Start();
for (var i = 0; i < n; i++)
    result = string.Format("{0} {1}", p.FirstName, p.LastName);
s.Stop();
fElapsedMilliseconds = s.ElapsedMilliseconds;
fElapsedTicks = s.ElapsedTicks;
s.Reset();


Console.Clear();
Console.WriteLine(n.ToString()+" x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");
Console.WriteLine(n.ToString() + " x result = (p.FirstName + \" \" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");
Thread.Sleep(4000);

Those are my results:

1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 618ms - 2213706 ticks
1000000 x result = (p.FirstName + " " + p.LastName); took: 166ms - 595610 ticks

Quinquefid answered 19/8, 2008 at 15:47 Comment(4)
Very interesting. I got an average of 224ms vs. 48ms, an x4.66 improvement, even better than your x3.72. I wonder if there is a post-compilation tool that can rewrite the IL of string.Format that doesn't use any composite formatting features (i.e. just simple {0}) and replace them with the considerably faster string concatenation. I wonder such a feat is achievable with an existing IL rewriter such as PostSharp.Confabulate
Strings are immutable, this means the same tiny piece of memory is used over and over in your code. Adding the same two strings together and creating the same new string over and over again doesn't impact memory. .Net is smart enough just to use the same memory reference. Therefore your code doesn't truly test the difference between the two concat methods. See code in my answer below.Stoeber
Honestly, I always concatenate since it's easier to read for me and wow it's faster :)Cookhouse
So speed is the only reason to choose one over the other?Subsist
S
55

Oh dear - after reading one of the other replies I tried reversing the order of the operations - so performing the concatenation first, then the String.Format...

Bill Gates
Console.WriteLine(p.FirstName + " " + p.LastName); took: 8ms - 30488 ticks
Bill Gates
Console.WriteLine("{0} {1}", p.FirstName, p.LastName); took: 0ms - 182 ticks

So the order of the operations makes a HUGE difference, or rather the very first operation is ALWAYS much slower.

Here are the results of a run where operations are completed more than once. I have tried changing the orders but things generally follow the same rules, once the first result is ignored:

Bill Gates
Console.WriteLine(FirstName + " " + LastName); took: 5ms - 20335 ticks
Bill Gates
Console.WriteLine(FirstName + " " + LastName); took: 0ms - 156 ticks
Bill Gates
Console.WriteLine(FirstName + " " + LastName); took: 0ms - 122 ticks
Bill Gates
Console.WriteLine("{0} {1}", FirstName, LastName); took: 0ms - 181 ticks
Bill Gates
Console.WriteLine("{0} {1}", FirstName, LastName); took: 0ms - 122 ticks
Bill Gates
String.Concat(FirstName, " ", LastName); took: 0ms - 142 ticks
Bill Gates
String.Concat(FirstName, " ", LastName); took: 0ms - 117 ticks

As you can see subsequent runs of the same method (I refactored the code into 3 methods) are incrementally faster. The fastest appears to be the Console.WriteLine(String.Concat(...)) method, followed by normal concatenation, and then the formatted operations.

The initial delay in startup is likely the initialisation of Console Stream, as placing a Console.Writeline("Start!") before the first operation brings all times back into line.

Sheepcote answered 19/8, 2008 at 15:47 Comment(2)
Then remove Console.WriteLine completely from your tests. It is skewing the results!Languedoc
I always start with a throwaway or "control" scenario when running performance tests for this exact reasonExsiccate
W
37

Strings are immutable, this means the same tiny piece of memory is used over and over in your code. Adding the same two strings together and creating the same new string over and over again doesn't impact memory. .Net is smart enough just to use the same memory reference. Therefore your code doesn't truly test the difference between the two concat methods.

Try this on for size:

Stopwatch s = new Stopwatch();

int n = 1000000;
long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0, sbElapsedMilliseconds = 0, sbElapsedTicks = 0;

Random random = new Random(DateTime.Now.Millisecond);

string result;
s.Start();
for (var i = 0; i < n; i++)
    result = (random.Next().ToString() + " " + random.Next().ToString());
s.Stop();
cElapsedMilliseconds = s.ElapsedMilliseconds;
cElapsedTicks = s.ElapsedTicks;
s.Reset();

s.Start();
for (var i = 0; i < n; i++)
    result = string.Format("{0} {1}", random.Next().ToString(), random.Next().ToString());
s.Stop();
fElapsedMilliseconds = s.ElapsedMilliseconds;
fElapsedTicks = s.ElapsedTicks;
s.Reset();

StringBuilder sb = new StringBuilder();
s.Start();
for(var i = 0; i < n; i++){
    sb.Clear();
    sb.Append(random.Next().ToString());
    sb.Append(" ");
    sb.Append(random.Next().ToString());
    result = sb.ToString();
}
s.Stop();
sbElapsedMilliseconds = s.ElapsedMilliseconds;
sbElapsedTicks = s.ElapsedTicks;
s.Reset();

Console.WriteLine(n.ToString() + " x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");
Console.WriteLine(n.ToString() + " x result = (p.FirstName + \" \" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");
Console.WriteLine(n.ToString() + " x sb.Clear();sb.Append(random.Next().ToString()); sb.Append(\" \"); sb.Append(random.Next().ToString()); result = sb.ToString(); took: " + (sbElapsedMilliseconds) + "ms - " + (sbElapsedTicks) + " ticks");
Console.WriteLine("****************");
Console.WriteLine("Press Enter to Quit");
Console.ReadLine();

Sample Output:

1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 513ms - 1499816 ticks
1000000 x result = (p.FirstName + " " + p.LastName); took: 393ms - 1150148 ticks
1000000 x sb.Clear();sb.Append(random.Next().ToString()); sb.Append(" "); sb.Append(random.Next().ToString()); result = sb.ToString(); took: 405ms - 1185816 ticks
Wifely answered 19/8, 2008 at 15:47 Comment(2)
Added a StringBuilder and sample output to the answerValerievalerio
I see how using string.Format is worth the tiny performance hit here. Architecturally it's better as it means you can alter the format more easily. But stringbuilder I really don't see the point of. Every other thread on here says you should use Stringbuilder instead of concatenating strings. What's the advantage? Clearly not speed, as this benchmark proves.Fractional
B
22

Pity the poor translators

If you know your application will stay in English, then fine, save the clock ticks. However, many cultures would usually see Lastname Firstname in, for instance, addresses.

So use string.Format(), especially if you're going to ever have your application go anywhere that English is not the first language.

Bergamo answered 19/8, 2008 at 15:47 Comment(4)
How would string.Format() behave different in different cultures? Wouldn't it still print first name then last name? It seems like you'd have to take the different culture into account in both situations. I feel like I'm missing something here.Brnaby
I agree with @DangerZone.. how would string.Format() know you were using a name for an address? If string.Format() swapped {0} {1} based on culture, I would consider it broken.Kansas
I believe the point that Jeremy was trying to make is that in the scenario described to support different countries it may be appropriate to extract out the format string itself to a language resource. For most countries that string would be "{0} {1}", but for the countries where surname-first is the typical operation (e.g. Hungary, Hong Kong, Cambodia, China, Japan, Korea, Madagascar, Taiwan, Vietnam, and parts of India) that string would be "{1} {0}" instead.Peltate
Indeed. Or, more subtly, add the format string as an attribute of the person. I, for instance, like to have my surname after my firstname, but my colleague Beng doesn't.Bergamo
T
14

Here are my results over 100,000 iterations:

Console.WriteLine("{0} {1}", p.FirstName, p.LastName); took (avg): 0ms - 689 ticks
Console.WriteLine(p.FirstName + " " + p.LastName); took (avg): 0ms - 683 ticks

And here is the bench code:

Stopwatch s = new Stopwatch();

var p = new { FirstName = "Bill", LastName = "Gates" };

//First print to remove the initial cost
Console.WriteLine(p.FirstName + " " + p.LastName);
Console.WriteLine("{0} {1}", p.FirstName, p.LastName);

int n = 100000;
long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;

for (var i = 0; i < n; i++)
{
    s.Start();
    Console.WriteLine(p.FirstName + " " + p.LastName);
    s.Stop();
    cElapsedMilliseconds += s.ElapsedMilliseconds;
    cElapsedTicks += s.ElapsedTicks;
    s.Reset();
    s.Start();
    Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
    s.Stop();
    fElapsedMilliseconds += s.ElapsedMilliseconds;
    fElapsedTicks += s.ElapsedTicks;
    s.Reset();
}

Console.Clear();

Console.WriteLine("Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName); took (avg): " + (fElapsedMilliseconds / n) + "ms - " + (fElapsedTicks / n) + " ticks");
Console.WriteLine("Console.WriteLine(p.FirstName + \" \" + p.LastName); took (avg): " + (cElapsedMilliseconds / n) + "ms - " + (cElapsedTicks / n) + " ticks");

So, I don't know whose reply to mark as an answer :)

Thumping answered 19/8, 2008 at 15:47 Comment(2)
Why is the background blue for this answer?Macri
@yossi it's blue because the answerer is the same as the askerFultz
F
9

Concatenating strings is fine in a simple scenario like that - it is more complicated with anything more complicated than that, even LastName, FirstName. With the format you can see, at a glance, what the final structure of the string will be when reading the code, with concatenation it becomes almost impossible to immediately discern the final result (except with a very simple example like this one).

What that means in the long run is that when you come back to make a change to your string format, you will either have the ability to pop in and make a few adjustments to the format string, or wrinkle your brow and start moving around all kinds of property accessors mixed with text, which is more likely to introduce problems.

If you're using .NET 3.5 you can use an extension method like this one and get an easy flowing, off the cuff syntax like this:

string str = "{0} {1} is my friend. {3}, {2} is my boss.".FormatWith(prop1,prop2,prop3,prop4);

Finally, as your application grows in complexity you may decide that to sanely maintain strings in your application you want to move them into a resource file to localize or simply into a static helper. This will be MUCH easier to achieve if you have consistently used formats, and your code can be quite simply refactored to use something like

string name = String.Format(ApplicationStrings.General.InformalUserNameFormat,this.FirstName,this.LastName);
Fabliau answered 19/8, 2008 at 15:47 Comment(0)
B
8

Starting from C# 6.0 interpolated strings can be used to do this, which simplifies the format even more.

var name = "Bill";
var surname = "Gates";
MessageBox.Show($"Welcome to the show, {name} {surname}!");

An interpolated string expression looks like a template string that contains expressions. An interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions’ results.

Interpolated strings have a similar performance to String.Format, but improved readability and shorter syntax, due to the fact that values and expressions are inserted in-line.

Please also refer to this dotnetperls article on string interpolation.

If you are looking for a default way to format your strings, this makes sense in terms of readability and performance (except if microseconds are going to make a difference in your specific use case).

Borrow answered 19/8, 2008 at 15:47 Comment(0)
T
7

For very simple manipulation I'd use concatenation, but once you get beyond 2 or 3 elements Format becomes more appropriate IMO.

Another reason to prefer String.Format is that .NET strings are immutable and doing it this way creates fewer temporary/intermediate copies.

Tamasha answered 19/8, 2008 at 15:47 Comment(0)
B
6

While I totally understand the style preference and picked concatenation for my first answer partly based on my own preference, part of my decision was based on the thought that concatenation would be faster. So, out of curiosity, I tested it and the results were staggering, especially for such a small string.

Using the following code:

    System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();

    var p = new { FirstName = "Bill", LastName = "Gates" };

    s.Start();
    Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
    s.Stop();
    Console.WriteLine("Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName); took: " + s.ElapsedMilliseconds + "ms - " + s.ElapsedTicks + " ticks");

    s.Reset();
    s.Start();
    Console.WriteLine(p.FirstName + " " + p.LastName);
    s.Stop();

    Console.WriteLine("Console.WriteLine(p.FirstName + \" \" + p.LastName); took: " + s.ElapsedMilliseconds + "ms - " + s.ElapsedTicks + " ticks");

I got the following results:

Bill Gates
Console.WriteLine("{0} {1}", p.FirstName, p.LastName); took: 2ms - 7280 ticks
Bill Gates
Console.WriteLine(p.FirstName + " " + p.LastName); took: 0ms - 67 ticks

Using the formatting method is over 100 times slower!! Concatenation didn't even register as 1ms, which is why I output the timer ticks as well.

Bloodless answered 19/8, 2008 at 15:47 Comment(3)
But of course you should perform the operation more than once to get measurements.Poco
And lose the call to Console.Writeline() since it is beyond the scope of the question?Contuse
did you test with a stringbuilder? ;)Subsist
J
5

A week from now Aug 19, 2015, this question will be exactly seven (7) years old. There is now a better way of doing this. Better in terms of maintainability as I haven't done any performance test compared to just concatenating strings (but does it matter these days? a few milliseconds in difference?). The new way of doing it with C# 6.0:

var p = new { FirstName = "Bill", LastName = "Gates" };
var fullname = $"{p.FirstName} {p.LastName}";

This new feature is better, IMO, and actually better in our case as we have codes where we build querystrings whose values depends on some factors. Imagine one querystring where we have 6 arguments. So instead of doing a, for example:

var qs = string.Format("q1={0}&q2={1}&q3={2}&q4={3}&q5={4}&q6={5}", 
    someVar, anotherVarWithLongName, var3, var4, var5, var6)

in can be written like this and it's easier to read:

var qs=$"q1={someVar}&q2={anotherVarWithLongName}&q3={var3}&q4={var4}&q5={var5}&q6={var6}";
Johnsten answered 19/8, 2008 at 15:47 Comment(4)
Indeed, the new way of C# 6.0 is better than previous alternatives - at least from a readability point of view.Thumping
That's right. And it's also safer as you don't have to be concerned about which object goes to which index (placeholder) since you will directly put the objects where you want it to be.Johnsten
BTW, it actually calls Format (at least with Roslyn).Thumping
BTW, what this poster is referring to is called "string interpolation", and is addressed elsewhere in this thread.Languedoc
G
5

A better test would be to watch your memory using Perfmon and the CLR memory counters. My understanding is that the whole reason you want to use String.Format instead of just concatenating strings is since strings are immutable, you are unnecessarily burdening the garbage collector with temporary strings that need to be reclaimed in the next pass.

StringBuilder and String.Format, although potentially slower, is more memory efficient.

What is so bad about string concatenation?

Gordon answered 19/8, 2008 at 15:47 Comment(1)
I Agree; every string operation creates a new copy of the string. All that memory will be reclaimed by the garbage collector sooner or later. So, allocating a lot of strings may come back to bite you later.Nickelodeon
B
5

For basic string concatenation, I generally use the second style - easier to read and simpler. However, if I am doing a more complicated string combination I usually opt for String.Format.

String.Format saves on lots of quotes and pluses...

Console.WriteLine("User {0} accessed {1} on {2}.", user.Name, fileName, timestamp);
vs
Console.WriteLine("User " + user.Name + " accessed " + fileName + " on " + timestamp + ".");

Only a few charicters saved, but I think, in this example, format makes it much cleaner.

Butterfingers answered 19/8, 2008 at 15:47 Comment(0)
S
5

Generally, I prefer the former, as especially when the strings get long it can be much easier to read.

The other benefit is I believe one of the performances, as the latter actually performs 2 string creation statements before passing the final string to the Console.Write method. String.Format uses a StringBuilder under the covers I believe, so multiple concatenations are avoided.

It should be noted however that if the parameters you are passing into String.Format (and other such methods like Console.Write) are value types then they will be boxed before passed in, which can provide its own performance hits. Blog post on this here.

Sheepcote answered 19/8, 2008 at 15:47 Comment(1)
That blog post is now at: jeffbarnes.net/blog/post/2006/08/08/…. I suffer from insufficient rep to edit.Perkoff
G
4

I choose based on readability. I prefer the format option when there's some text around the variables. In this example:

Console.WriteLine("User {0} accessed {1} on {2}.", 
                   user.Name, fileName, timestamp);

you understand the meaning even without variable names, whereas the concat is cluttered with quotes and + signs and confuses my eyes:

Console.WriteLine("User " + user.Name + " accessed " + fileName + 
                  " on " + timestamp + ".");

(I borrowed Mike's example because I like it)

If the format string doesn't mean much without variable names, I have to use concat:

Console.WriteLine("{0} {1}", p.FirstName, p.LastName);

The format option makes me read the variable names and map them to the corresponding numbers. The concat option doesn't require that. I'm still confused by the quotes and + signs, but the alternative is worse. Ruby?

Console.WriteLine(p.FirstName + " " + p.LastName);

Performance-wise, I expect the format option to be slower than the concat, since the format requires the string to be parsed. I don't remember having to optimize this kind of instruction, but if I did, I'd look at string methods like Concat() and Join().

The other advantage of the format is that the format string can be put in a configuration file. Very handy with error messages and UI text.

Gittens answered 19/8, 2008 at 15:47 Comment(0)
A
4

I'd use the String.Format, but I would also have the format string in the resource files so it can be localised for other languages. Using a simple string concat doesn't allow you to do that. Obviously, if you won't ever need to localise that string, this isn't a reason to think about it. It really depends on what the string is for.

If it's going to be shown to the user, I'd use String.Format so I can localize if I need to - and FxCop will spell-check it for me, just in case :)

If it contains numbers or any other non-string things (e.g. dates), I'd use String.Format because it gives me more control over the formatting.

If it's for building a query like SQL, I'd use Linq.

If for concatenating strings inside a loop, I'd use StringBuilder to avoid performance problems.

If it's for some output the user won't see and isn't going to affect performance I'd use String.Format because I'm in the habit of using it anyway and I'm just used to it :)

Aponte answered 19/8, 2008 at 15:47 Comment(0)
A
4
  1. Formatting is the “.NET” way of doing it. Certain refactoring tools (Refactor! for one) will even propose to refactor the concat-style code to use the formatting style.
  2. Formatting is easier to optimize for the compiler (although the second will probably be refactored to use the 'Concat' method which is fast).
  3. Formatting is usually clearer to read (especially with “fancy” formatting).
  4. Formatting means implicit calls to '.ToString' on all variables, which is good for readability.
  5. According to “Effective C#”, the .NET 'WriteLine' and 'Format' implementations are messed up, they autobox all value types (which is bad). “Effective C#” advises to perform '.ToString' calls explicitly, which IMHO is bogus (see Jeff's posting)
  6. At the moment, formatting type hints are not checked by the compiler, resulting in runtime errors. However, this could be amended in future versions.
Alisealisen answered 19/8, 2008 at 15:47 Comment(0)
D
3

If you intend to localise the result, then String.Format is essential because different natural languages might not even have the data in the same order.

Deontology answered 19/8, 2008 at 15:47 Comment(0)
W
3

If you're dealing with something that needs to be easy to read (and this is most code), I'd stick with the operator overload version UNLESS:

  • The code needs to be executed millions of times
  • You're doing tons of concats (more than 4 is a ton)
  • The code is targeted towards the Compact Framework

Under at least two of these circumstances, I would use StringBuilder instead.

Where answered 19/8, 2008 at 15:47 Comment(0)
W
2

Since I don't think the answers here cover everything, I'd like to make a small addition here.

Console.WriteLine(string format, params object[] pars) calls string.Format. The '+' implies string concatenation. I don't think this always has to do with style; I tend to mix the two styles depending on the context I'm in.

Short answer

The decision you're facing has to do with string allocation. I'll try to make it simple.

Say you have

string s = a + "foo" + b;

If you execute this, it will evaluate as follows:

string tmp1 = a;
string tmp2 = "foo" 
string tmp3 = concat(tmp1, tmp2);
string tmp4 = b;
string s = concat(tmp3, tmp4);

tmp here is not really a local variable, but it is temporary for the JIT (it's pushed on the IL stack). If you push a string on the stack (such as ldstr in IL for literals), you put a reference to a string pointer on the stack.

The moment you call concat this reference becomes a problem because there isn't any string reference available that contains both strings. This means that .NET needs to allocate a new block of memory, and then fill it with the two strings. The reason this is a problem is that allocation is relatively expensive.

Which changes the question to: How can you reduce the number of concat operations?

So, the rough answer is: string.Format for >1 concats, '+' will work just fine for 1 concat. And if you don't care about doing micro-performance optimizations, string.Format will work just fine in the general case.

A note about Culture

And then there's something called culture...

string.Format enables you to use CultureInfo in your formatting. A simple operator '+' uses the current culture.

This is especially an important remark if you're writing file formats and f.ex. double values that you 'add' to a string. On different machines, you might end up with different strings if you don't use string.Format with an explicit CultureInfo.

F.ex. consider what happens if you change a '.' for a ',' while writing your comma-seperated-values file... in Dutch, the decimal separator is a comma, so your user might just get a 'funny' surprise.

More detailed answer

If you don't know the exact size of the string beforehand, it's best to use a policy like this to over allocate the buffers you use. The slack space is first filled, after which the data is copied in.

Growing means allocating a new block of memory and copying the old data to the new buffer. The old block of memory can then be released. You get the bottom line at this point: growing is an expensive operation.

The most practical way to do this is to use an overallocation policy. The most common policy is to over allocate buffers in powers of 2. Of course, you have to do it a bit smarter than that (since it makes no sense to grow from 1,2,4,8 if you already know you need 128 chars) but you get the picture. The policy ensures you don't need too many of the expensive operations I described above.

StringBuilder is a class that basically over allocates the underlying buffer in powers of two. string.Format uses StringBuilder under the hood.

This makes your decision a basic trade-off between over-allocate-and-append (-multiple) (w/w.o. culture) or just allocate-and-append.

Wallford answered 19/8, 2008 at 15:47 Comment(0)
T
2

Nice one!

Just added

        s.Start();
        for (var i = 0; i < n; i++)
            result = string.Concat(p.FirstName, " ", p.LastName);
        s.Stop();
        ceElapsedMilliseconds = s.ElapsedMilliseconds;
        ceElapsedTicks = s.ElapsedTicks;
        s.Reset();

And it is even faster (I guess string.Concat is called in both examples, but the first one requires some sort of translation).

1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 249ms - 3571621 ticks
1000000 x result = (p.FirstName + " " + p.LastName); took: 65ms - 944948 ticks
1000000 x result = string.Concat(p.FirstName, " ", p.LastName); took: 54ms - 780524 ticks
Thumping answered 19/8, 2008 at 15:47 Comment(1)
It takes exactly the same amount of time since operator-based string concatenations is translated by the compiler to calls to string.Concat(...). It is done during compilation so it has no impact on run-time performance. If you run your tests multiple times or run them on a larger test samples you will see they are identical.Confabulate
N
2

I prefer the second as well but I have no rational arguments at this time to support that position.

Neutral answered 19/8, 2008 at 15:47 Comment(0)
S
2

I think this depends heavily on how complex the output is. I tend to choose whichever scenario works best at the time.

Pick the right tool based on the job :D Whichever looks cleanest!

Strachan answered 19/8, 2008 at 15:47 Comment(0)
D
1

The most readable would be to use the string interpolation feature of C# 6.0:

Console.WriteLine($"{p.FirstName} {p.LastName}");

Its performance is similar to using "+".

Dapplegray answered 19/8, 2008 at 15:47 Comment(0)
C
1

According to the MCSD prep material, Microsoft suggests using the + operator when dealing with a very small number of concatenations (probably 2 to 4). I'm still not sure why, but it's something to consider.

Cubit answered 19/8, 2008 at 15:47 Comment(0)
S
1

I was curious where StringBuilder stood with these tests. Results below...

class Program {
   static void Main(string[] args) {

      var p = new { FirstName = "Bill", LastName = "Gates" };

      var tests = new[] {
         new { Name = "Concat", Action = new Action(delegate() { string x = p.FirstName + " " + p.LastName; }) },
         new { Name = "Format", Action = new Action(delegate() { string x = string.Format("{0} {1}", p.FirstName, p.LastName); }) },
         new { Name = "StringBuilder", Action = new Action(delegate() {
            StringBuilder sb = new StringBuilder();
            sb.Append(p.FirstName);
            sb.Append(" ");
            sb.Append(p.LastName);
            string x = sb.ToString();
         }) }
      };

      var Watch = new Stopwatch();
      foreach (var t in tests) {
         for (int i = 0; i < 5; i++) {
            Watch.Reset();
            long Elapsed = ElapsedTicks(t.Action, Watch, 10000);
            Console.WriteLine(string.Format("{0}: {1} ticks", t.Name, Elapsed.ToString()));
         }
      }
   }

   public static long ElapsedTicks(Action ActionDelg, Stopwatch Watch, int Iterations) {
      Watch.Start();
      for (int i = 0; i < Iterations; i++) {
         ActionDelg();
      }
      Watch.Stop();
      return Watch.ElapsedTicks / Iterations;
   }
}

Results:

Concat: 406 ticks
Concat: 356 ticks
Concat: 411 ticks
Concat: 299 ticks
Concat: 266 ticks
Format: 5269 ticks
Format: 954 ticks
Format: 1004 ticks
Format: 984 ticks
Format: 974 ticks
StringBuilder: 629 ticks
StringBuilder: 484 ticks
StringBuilder: 482 ticks
StringBuilder: 508 ticks
StringBuilder: 504 ticks
Suburbanite answered 19/8, 2008 at 15:47 Comment(0)
T
1

The first one (format) looks better to me. It's more readable and you are not creating extra temporary string objects.

Trailer answered 19/8, 2008 at 15:47 Comment(0)
S
1

Oh, and just for completeness, the following is a few ticks faster than normal concatenation:

Console.WriteLine(String.Concat(p.FirstName," ",p.LastName));
Sheepcote answered 19/8, 2008 at 15:47 Comment(0)
A
1

I've always gone the string.Format() route. Being able to store formats in variables like Nathan's example is a great advantage. In some cases I may append a variable but once more than 1 variable is being concatenated I refactor to use formatting.

Afflux answered 19/8, 2008 at 15:47 Comment(0)
S
1

I actually like the first one because when there are a lot of variables intermingled with the text it seems easier to read to me. Plus, it is easier to deal with quotes when using the string.Format(), uh, format. Here is decent analysis of string concatenation.

Sanctimonious answered 19/8, 2008 at 15:47 Comment(0)
B
1

Personally, the second one as everything you are using is in the direct order it will be output in. Whereas with the first you have to match up the {0} and {1} with the proper var, which is easy to mess up.

At least it's not as bad as the C++ sprint where if you get the variable type wrong the whole thing will blow up.

Also, since the second is all inline and it doesn't have to do any searching and replacing for all the {0} things, the latter should be faster... though I don't know for sure.

Bloodless answered 19/8, 2008 at 15:47 Comment(0)
T
0

Actually, I ran these tests yesterday, but it was getting late so I didnt put my responses.

The bottom line seems that they take both the same time on average. I did the test over 100000 iterations.

I'll try with StringBuilder as well, and I'll post the code and results when I get home.

Thumping answered 19/8, 2008 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.