9

What are the pros/cons (if any) to using

string output; 
int i = 10;
output = string.Format("the int is {0}", i);

versus

string output; 
int i = 10;
output = "the int is " + i;

I have always used the latter example, but it seems as though a good majority of online tutorials use the string.format example. I don't think that there are any real differences in terms of efficiency, my initial thought is so a coder doesn't have to keep breaking the string to insert variables.

Bernard
  • 8,859
  • 31
  • 40
Jim
  • 641
  • 1
  • 5
  • 18
  • 8
    The main reason is that it makes translation much easier, because your program does not need to understand the way different languages build up their sentences. For example, many expressions and phrases in French are back-to-front compared to their English translations. – JohnL Jan 26 '12 at 18:28
  • As of C# 6 you can now use string interpolation. See: https://stackoverflow.com/questions/32342392/string-interpolation-vs-string-format and https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated for details. This should be an answer but could not add. – AnthonyVO Feb 11 '23 at 16:00

7 Answers7

22

If you consider translation to be important in your project, the first syntax will really help with it.

For instance you may have:

static final string output_en = "{0} is {1} years old.";
static final string output_fr = "{0} a {1} ans.";

int age = 10;
string name = "Henri";
System.out.println(string.Format(output_en, name, age));
System.out.println(string.Format(output_fr, name, age));

Also note that your variables may not always be in the same place in the sentence with that syntax:

static final string output_yoda = "{1} years {0} has.";
toastifer
  • 147
  • 6
Alex Garcia
  • 388
  • 2
  • 10
8

Check out the first answer for https://stackoverflow.com/questions/4671610/why-use-string-format. It covers everything in my opinion as to why it is better.

Also, each .NET assembly has an intern pool, containing a collection of unique strings. When your code is compiled, all the string literals you reference in your code are added to this pool. If you have a code that looks like this:

"the int is " + i + " and the double is " + d

That makes it 2 strings in the pool.

If you have:

"the int is {0} and the double is {1}"

You have only one String in the pool.

It is a bit more complicated to know when Strings are interned, and when they are not because the compiler has some intelligence when detecting Strings that may not need to be interned sometimes...Check out for example this article which gives more insight into this matter.

Edit: after digging up a bit, I've encountered an interesting answer to the question When is it better to use String.Format vs string concatenation?. In short, the author of the answer with +30 votes makes a compelling argument in favor of String concatenation when localization is not involved.

Jalayn
  • 9,789
  • 4
  • 39
  • 58
4

I prefer the first way because it allows me to accurately see what the string is going to look like when output. It's very easy to forget to add a space, or to add extra spacing when just appending strings.

I'm sure that there's also a performance benefit to the first way due to not having to create the extra strings; but that's not my primary concern.

John Kraft
  • 1,366
  • 8
  • 13
2

By using the first option you can store a commonly used format string and reduce typing needed and make it easier to update the string everywhere its used. Basically the first option allows for DRY to be implemented easily. It is also a much nicer syntax if multiple variables need to be used in a string, like you mentioned.

Ryathal
  • 13,317
  • 1
  • 33
  • 48
  • ahh I see, I guess I didn't think of the example: string.format("the int is {0}. again it is {0}", int); – Jim Jan 26 '12 at 16:59
1

I think with string.Format() it's easier to see what exactly is the result going to be (so you don't have problems with forgotten spaces or something like that), and it's also easier to type and modify.

If you want to do very simple formatting, using the + plus operator might be easier, but I tend to use it only when concatenating two strings, not more.

To show how string.Format() is easier to modify, consider that you wanted to add a full stop at the end of the sentence in your example: going from string.Format("The int is {0}", i) to string.Format("The int is {0}.", i) is just one character. But going from "the int is " + i to "the int is " + i + '.' is much more.

Another advantage of string.Format() is that it allows you to easily specify the format to use, like string.Format("The int is 0x{0:X}.", i). This is even more important when formatting date.

As for efficiency, string.Format() is most likely slower that simple string concatenations. But code like this is most likely not on a hot path, so it doesn't matter. And if it does, you are probably better off with using StringBuilder.

svick
  • 9,999
  • 1
  • 37
  • 51
1

Use the one that makes your code most readable. Don't worry about performance.

For your example below I prefer B because it is just more readable. But the language translations above also makes sense. Don't let anyone force you into using string.Format, instead read and point to Jeff Atwoods excellent blog on the The Sad Tragedy of Micro Optimizations Theater

A:

string output; 
int i = 10;
output = string.Format("the int is {0}", i);

versus

B:

string output; 
int i = 10;
output = "the int is " + i;
Mark Booth
  • 14,214
  • 3
  • 40
  • 79
Makach
  • 577
  • 3
  • 13
-1

Ref: String output: format or concat in C#?

Consider this code.

It's a slightly modified version of your code.

  1. I removed Console.WriteLine as it's probably few orders of magnitude slower than what I'm trying to measure.
  2. I'm staring 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 result by number of iterations was wrong. See what hapens if you have 1000 milliseconds and 100 milliseconds. In both situations you will get 0 ms after dividing it by 1000000.
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
jp2code
  • 99
  • 4
  • 1
    How does this answer the aspects of if the first code example or the second code example is a better design? How does a half second over 1M iterations account for if this is easier code for a person to maintain or not? –  Oct 28 '15 at 18:22
  • Jim asked, "What are the pros and cons?" This shows that over many iterations, **String.Format** is faster. – jp2code Oct 28 '15 at 22:03
  • You should consider fully adding that to your answer rather than leaving it as a block of code and differences from the OP's code. As it stands, your answer doesn't answer the OP's question in English. Look at the other answers. It would be possible to remove all the code from them and still have an answer to the OP's question. –  Oct 28 '15 at 22:13