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.

2
  • 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
    Commented Jan 26, 2012 at 18:28
  • As of C# 6 you can now use string interpolation. See: stackoverflow.com/questions/32342392/… and learn.microsoft.com/en-us/dotnet/csharp/language-reference/… for details. This should be an answer but could not add.
    – AnthonyVO
    Commented Feb 11, 2023 at 16:00

7 Answers 7

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.";
5
  • 4
    +1 for using Yoda-speak as an example of object-subject-verb syntax. Commented Oct 23, 2015 at 19:16
  • 1
    With C# we have a new option: System.out.println($"{name} is {age} year's old."); Commented Dec 20, 2017 at 18:04
  • See: informit.com/articles/article.aspx?p=2422807 Commented Dec 20, 2017 at 18:06
  • @BerinLoritsch: which is completely unusable for localization, unfortunately. Commented Dec 21, 2017 at 20:40
  • @BryanBoettcher, understood, but I didn't see anything in the OP saying that's what they were trying to accomplish. Commented Dec 22, 2017 at 12:49
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.

2
  • 2
    I think also, stylistically, it resonates with people i.e. people like me, who are used to printf and sprintf from c. Commented Jan 26, 2012 at 18:26
  • I would have liked to know why the downvote in order to fix my answer. Thanks.
    – Jalayn
    Commented Jan 27, 2012 at 7:23
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.

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.

1
  • ahh I see, I guess I didn't think of the example: string.format("the int is {0}. again it is {0}", int);
    – Jim
    Commented Jan 26, 2012 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.

1
  • string.Format internally uses a StringBuilder anyway Commented Dec 21, 2017 at 20:41
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;
-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
3
  • 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?
    – user40980
    Commented Oct 28, 2015 at 18:22
  • Jim asked, "What are the pros and cons?" This shows that over many iterations, String.Format is faster.
    – jp2code
    Commented Oct 28, 2015 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.
    – user40980
    Commented Oct 28, 2015 at 22:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.