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

<ul>
<li><p><code>var p = new { FirstName = "Bill", LastName = "Gates" };</code></p></li>
<li><p><code>Console.WriteLine("{0} {1}", p.FirstName, p.LastName);</code></p></li>
<li><p><code>Console.WriteLine(p.FirstName + " " + p.LastName);</code></p></li>
</ul>

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

<p>Do you have any rational arguments to use one and not the other?</p>

<p>I'd go for the second one.</p>

[{'answer_id': 16436, 'author': 'Adam Haile', 'author_id': 194, 'author_profile': 'https://Stackoverflow.com/users/194', 'pm_score': 1, 'selected': False, 'text': "<p>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.</p>\n<p>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.</p>\n<p>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.</p>\n"}, {'answer_id': 16437, 'author': 'mercutio', 'author_id': 1951, 'author_profile': 'https://Stackoverflow.com/users/1951', 'pm_score': 2, 'selected': False, 'text': '<p>I think this depends heavily on how complex the output is. I tend to choose whichever scenario works best at the time.</p>\n\n<p>Pick the right tool based on the job :D Whichever looks cleanest!</p>\n'}, {'answer_id': 16438, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>For very simple manipulation I'd use concatenation, but once you get beyond 2 or 3 elements Format becomes more appropriate IMO.</p>\n\n<p>Another reason to prefer String.Format is that .NET strings are immutable and doing it this way creates fewer temporary/intermediate copies.</p>\n"}, {'answer_id': 16441, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I prefer the second as well but I have no rational arguments at this time to support that position.</p>\n'}, {'answer_id': 16449, 'author': 'samjudson', 'author_id': 1908, 'author_profile': 'https://Stackoverflow.com/users/1908', 'pm_score': 3, 'selected': False, 'text': '<p>Generally, I prefer the former, as especially when the strings get long it can be much easier to read.</p>\n<p>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 <code>Console.Write</code> method. <code>String.Format</code> uses a StringBuilder under the covers I believe, so multiple concatenations are avoided.</p>\n<p>It should be noted however that if the parameters you are passing into <code>String.Format</code> (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. <a href="http://jeffbarnes.net/blog/post/2006/08/08/Avoid-Boxing-When-Using-StringFormat-with-Value-Types.aspx" rel="nofollow noreferrer">Blog post on this here</a>.</p>\n'}, {'answer_id': 16452, 'author': 'Mike', 'author_id': 1573, 'author_profile': 'https://Stackoverflow.com/users/1573', 'pm_score': 3, 'selected': False, 'text': '<p>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.  </p>\n\n<p>String.Format saves on lots of quotes and pluses...</p>\n\n<pre><code>Console.WriteLine("User {0} accessed {1} on {2}.", user.Name, fileName, timestamp);\nvs\nConsole.WriteLine("User " + user.Name + " accessed " + fileName + " on " + timestamp + ".");\n</code></pre>\n\n<p>Only a few charicters saved, but I think, in this example, format  makes it much cleaner.</p>\n'}, {'answer_id': 16455, 'author': 'Nathan', 'author_id': 541, 'author_profile': 'https://Stackoverflow.com/users/541', 'pm_score': 3, 'selected': False, 'text': '<p>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).</p>\n\n<p>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.</p>\n\n<p>If you\'re using .NET 3.5 you can use an extension method <a href="http://james.newtonking.com/archive/2008/03/27/formatwith-string-format-extension-method.aspx" rel="noreferrer">like this one</a> and get an easy flowing, off the cuff syntax like this:</p>\n\n<pre><code>string str = "{0} {1} is my friend. {3}, {2} is my boss.".FormatWith(prop1,prop2,prop3,prop4);\n</code></pre>\n\n<p>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</p>\n\n<pre><code>string name = String.Format(ApplicationStrings.General.InformalUserNameFormat,this.FirstName,this.LastName);\n</code></pre>\n'}, {'answer_id': 16457, 'author': 'adparadox', 'author_id': 1962, 'author_profile': 'https://Stackoverflow.com/users/1962', 'pm_score': 1, 'selected': False, 'text': '<p>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 <a href="http://blog.cumps.be/string-concatenation-vs-memory-allocation/" rel="nofollow noreferrer">decent analysis</a> of string concatenation.</p>\n'}, {'answer_id': 16463, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 2, 'selected': False, 'text': '<ol>\n<li>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.</li>\n<li>Formatting is easier to optimize for the compiler (although the second will probably be refactored to use the \'Concat\' method which is fast).</li>\n<li>Formatting is usually clearer to read (especially with “fancy” formatting).</li>\n<li>Formatting means implicit calls to \'.ToString\' on all variables, which is good for readability.</li>\n<li>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 <a href="http://www.codinghorror.com/blog/archives/000878.html" rel="nofollow noreferrer">Jeff\'s posting</a>)</li>\n<li>At the moment, formatting type hints are not checked by the compiler, resulting in runtime errors. However, this could be amended in future versions.</li>\n</ol>\n'}, {'answer_id': 16471, 'author': 'Adam Haile', 'author_id': 194, 'author_profile': 'https://Stackoverflow.com/users/194', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<p>Using the following code:</p>\n\n<pre><code>    System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();\n\n    var p = new { FirstName = "Bill", LastName = "Gates" };\n\n    s.Start();\n    Console.WriteLine("{0} {1}", p.FirstName, p.LastName);\n    s.Stop();\n    Console.WriteLine("Console.WriteLine(\\"{0} {1}\\", p.FirstName, p.LastName); took: " + s.ElapsedMilliseconds + "ms - " + s.ElapsedTicks + " ticks");\n\n    s.Reset();\n    s.Start();\n    Console.WriteLine(p.FirstName + " " + p.LastName);\n    s.Stop();\n\n    Console.WriteLine("Console.WriteLine(p.FirstName + \\" \\" + p.LastName); took: " + s.ElapsedMilliseconds + "ms - " + s.ElapsedTicks + " ticks");\n</code></pre>\n\n<p>I got the following results:</p>\n\n<pre><code>Bill Gates\nConsole.WriteLine("{0} {1}", p.FirstName, p.LastName); took: 2ms - 7280 ticks\nBill Gates\nConsole.WriteLine(p.FirstName + " " + p.LastName); took: 0ms - 67 ticks\n</code></pre>\n\n<p>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.</p>\n'}, {'answer_id': 16480, 'author': 'Wilka', 'author_id': 1367, 'author_profile': 'https://Stackoverflow.com/users/1367', 'pm_score': 2, 'selected': False, 'text': '<p>I\'d use the <code>String.Format</code>, 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.</p>\n<p>If it\'s going to be shown to the user, I\'d use <code>String.Format</code> so I can localize if I need to - and <a href="http://msdn.microsoft.com/en-us/library/bb429476.aspx" rel="nofollow noreferrer">FxCop</a> will spell-check it for me, just in case :)</p>\n<p>If it contains numbers or any other non-string things (e.g. dates), I\'d use <code>String.Format</code> because it gives me more <a href="http://www.sellsbrothers.com/tools/#FormatDesigner" rel="nofollow noreferrer">control over the formatting</a>.</p>\n<p>If it\'s for building a query like SQL, I\'d use <a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx" rel="nofollow noreferrer">Linq</a>.</p>\n<p>If for concatenating strings inside a loop, I\'d use <a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx" rel="nofollow noreferrer">StringBuilder</a> to avoid performance problems.</p>\n<p>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 :)</p>\n'}, {'answer_id': 16766, 'author': 'Scott Muc', 'author_id': 1894, 'author_profile': 'https://Stackoverflow.com/users/1894', 'pm_score': 1, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 17608, 'author': 'samjudson', 'author_id': 1908, 'author_profile': 'https://Stackoverflow.com/users/1908', 'pm_score': 1, 'selected': False, 'text': '<p>Oh, and just for completeness, the following is a few ticks faster than normal concatenation:</p>\n\n<pre><code>Console.WriteLine(String.Concat(p.FirstName," ",p.LastName));\n</code></pre>\n'}, {'answer_id': 17615, 'author': 'samjudson', 'author_id': 1908, 'author_profile': 'https://Stackoverflow.com/users/1908', 'pm_score': 6, 'selected': False, 'text': '<p>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...</p>\n<pre><code>Bill Gates\nConsole.WriteLine(p.FirstName + &quot; &quot; + p.LastName); took: 8ms - 30488 ticks\nBill Gates\nConsole.WriteLine(&quot;{0} {1}&quot;, p.FirstName, p.LastName); took: 0ms - 182 ticks\n</code></pre>\n<p>So the order of the operations makes a HUGE difference, or rather the very first operation is ALWAYS much slower.</p>\n<p>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:</p>\n<pre><code>Bill Gates\nConsole.WriteLine(FirstName + &quot; &quot; + LastName); took: 5ms - 20335 ticks\nBill Gates\nConsole.WriteLine(FirstName + &quot; &quot; + LastName); took: 0ms - 156 ticks\nBill Gates\nConsole.WriteLine(FirstName + &quot; &quot; + LastName); took: 0ms - 122 ticks\nBill Gates\nConsole.WriteLine(&quot;{0} {1}&quot;, FirstName, LastName); took: 0ms - 181 ticks\nBill Gates\nConsole.WriteLine(&quot;{0} {1}&quot;, FirstName, LastName); took: 0ms - 122 ticks\nBill Gates\nString.Concat(FirstName, &quot; &quot;, LastName); took: 0ms - 142 ticks\nBill Gates\nString.Concat(FirstName, &quot; &quot;, LastName); took: 0ms - 117 ticks\n</code></pre>\n<p>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.</p>\n<p>The initial delay in startup is likely the initialisation of Console Stream, as placing a Console.Writeline(&quot;Start!&quot;) before the first operation brings all times back into line.</p>\n'}, {'answer_id': 17976, 'author': 'Philippe', 'author_id': 920, 'author_profile': 'https://Stackoverflow.com/users/920', 'pm_score': 0, 'selected': False, 'text': "<p>Actually, I ran these tests yesterday, but it was getting late so I didnt put my responses.</p>\n\n<p>The bottom line seems that they take both the same time on average. I did the test over 100000 iterations.</p>\n\n<p>I'll try with StringBuilder as well, and I'll post the code and results when I get home.</p>\n"}, {'answer_id': 18300, 'author': 'Philippe', 'author_id': 920, 'author_profile': 'https://Stackoverflow.com/users/920', 'pm_score': 4, 'selected': False, 'text': '<p>Here are my results over 100,000 iterations:</p>\n\n<pre><code>Console.WriteLine("{0} {1}", p.FirstName, p.LastName); took (avg): 0ms - 689 ticks\nConsole.WriteLine(p.FirstName + " " + p.LastName); took (avg): 0ms - 683 ticks\n</code></pre>\n\n<p>And here is the bench code:</p>\n\n<pre><code>Stopwatch s = new Stopwatch();\n\nvar p = new { FirstName = "Bill", LastName = "Gates" };\n\n//First print to remove the initial cost\nConsole.WriteLine(p.FirstName + " " + p.LastName);\nConsole.WriteLine("{0} {1}", p.FirstName, p.LastName);\n\nint n = 100000;\nlong fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;\n\nfor (var i = 0; i &lt; n; i++)\n{\n    s.Start();\n    Console.WriteLine(p.FirstName + " " + p.LastName);\n    s.Stop();\n    cElapsedMilliseconds += s.ElapsedMilliseconds;\n    cElapsedTicks += s.ElapsedTicks;\n    s.Reset();\n    s.Start();\n    Console.WriteLine("{0} {1}", p.FirstName, p.LastName);\n    s.Stop();\n    fElapsedMilliseconds += s.ElapsedMilliseconds;\n    fElapsedTicks += s.ElapsedTicks;\n    s.Reset();\n}\n\nConsole.Clear();\n\nConsole.WriteLine("Console.WriteLine(\\"{0} {1}\\", p.FirstName, p.LastName); took (avg): " + (fElapsedMilliseconds / n) + "ms - " + (fElapsedTicks / n) + " ticks");\nConsole.WriteLine("Console.WriteLine(p.FirstName + \\" \\" + p.LastName); took (avg): " + (cElapsedMilliseconds / n) + "ms - " + (cElapsedTicks / n) + " ticks");\n</code></pre>\n\n<p>So, I don\'t know whose reply to mark as an answer :)</p>\n'}, {'answer_id': 18342, 'author': 'Michał Piaskowski', 'author_id': 1534, 'author_profile': 'https://Stackoverflow.com/users/1534', 'pm_score': 7, 'selected': True, 'text': "<p>Try this code.</p>\n<p>It's a slightly modified version of your code.<BR></p>\n<ol>\n<li>I removed Console.WriteLine as it's probably a few orders of magnitude slower than what I'm trying to measure.<BR></li>\n<li>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. <BR></li>\n<li>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.</li>\n</ol>\n<p>Code:</p>\n<pre><code>Stopwatch s = new Stopwatch();\n\nvar p = new { FirstName = &quot;Bill&quot;, LastName = &quot;Gates&quot; };\n\nint n = 1000000;\nlong fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;\n\nstring result;\ns.Start();\nfor (var i = 0; i &lt; n; i++)\n    result = (p.FirstName + &quot; &quot; + p.LastName);\ns.Stop();\ncElapsedMilliseconds = s.ElapsedMilliseconds;\ncElapsedTicks = s.ElapsedTicks;\ns.Reset();\ns.Start();\nfor (var i = 0; i &lt; n; i++)\n    result = string.Format(&quot;{0} {1}&quot;, p.FirstName, p.LastName);\ns.Stop();\nfElapsedMilliseconds = s.ElapsedMilliseconds;\nfElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\n\nConsole.Clear();\nConsole.WriteLine(n.ToString()+&quot; x result = string.Format(\\&quot;{0} {1}\\&quot;, p.FirstName, p.LastName); took: &quot; + (fElapsedMilliseconds) + &quot;ms - &quot; + (fElapsedTicks) + &quot; ticks&quot;);\nConsole.WriteLine(n.ToString() + &quot; x result = (p.FirstName + \\&quot; \\&quot; + p.LastName); took: &quot; + (cElapsedMilliseconds) + &quot;ms - &quot; + (cElapsedTicks) + &quot; ticks&quot;);\nThread.Sleep(4000);\n</code></pre>\n<p>Those are my results:</p>\n<blockquote>\n<p>1000000 x result = string.Format(&quot;{0} {1}&quot;, p.FirstName, p.LastName); took: 618ms - 2213706 ticks<br />\n1000000 x result = (p.FirstName + &quot; &quot; + p.LastName); took: 166ms - 595610 ticks</p>\n</blockquote>\n"}, {'answer_id': 18467, 'author': 'Philippe', 'author_id': 920, 'author_profile': 'https://Stackoverflow.com/users/920', 'pm_score': 2, 'selected': False, 'text': '<p>Nice one!</p>\n\n<p>Just added</p>\n\n<pre><code>        s.Start();\n        for (var i = 0; i &lt; n; i++)\n            result = string.Concat(p.FirstName, " ", p.LastName);\n        s.Stop();\n        ceElapsedMilliseconds = s.ElapsedMilliseconds;\n        ceElapsedTicks = s.ElapsedTicks;\n        s.Reset();\n</code></pre>\n\n<p>And it is even faster (I guess string.Concat is called in both examples, but the first one requires some sort of translation).</p>\n\n<pre><code>1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 249ms - 3571621 ticks\n1000000 x result = (p.FirstName + " " + p.LastName); took: 65ms - 944948 ticks\n1000000 x result = string.Concat(p.FirstName, " ", p.LastName); took: 54ms - 780524 ticks\n</code></pre>\n'}, {'answer_id': 24547, 'author': 'Rismo', 'author_id': 1560, 'author_profile': 'https://Stackoverflow.com/users/1560', 'pm_score': 1, 'selected': False, 'text': "<p>The first one (format) looks better to me. It's more readable and you are not creating extra temporary string objects.</p>\n"}, {'answer_id': 24561, 'author': 'Fredrik Kalseth', 'author_id': 1710, 'author_profile': 'https://Stackoverflow.com/users/1710', 'pm_score': 7, 'selected': False, 'text': '<p>I\'m amazed that so many people immediately want to find the code that executes the fastest. <em>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.</em> </p>\n\n<blockquote>\n  <p>Premature optimization = FAIL.</p>\n</blockquote>\n\n<p>I\'d go with the <code>String.Format</code> 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...)</p>\n\n<p>Consider if your customer later wants to change it so that they can configure whether to display <code>"Firstname Lastname"</code> or <code>"Lastname, Firstname."</code> 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.</p>\n'}, {'answer_id': 115135, 'author': 'David Hill', 'author_id': 1181217, 'author_profile': 'https://Stackoverflow.com/users/1181217', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n<p>StringBuilder and String.Format, although potentially slower, is more memory efficient.</p>\n<p><a href="http://geertverhoeven.blogspot.com/2007/01/what-is-so-bad-about-string.html" rel="nofollow noreferrer">What is so bad about string concatenation?</a></p>\n'}, {'answer_id': 115239, 'author': 'plinth', 'author_id': 20481, 'author_profile': 'https://Stackoverflow.com/users/20481', 'pm_score': 2, 'selected': False, 'text': "<p>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:</p>\n\n<ul>\n<li>The code needs to be executed millions of times</li>\n<li>You're doing tons of concats (more than 4 is a ton)</li>\n<li>The code is targeted towards the Compact Framework</li>\n</ul>\n\n<p>Under at least two of these circumstances, I would use StringBuilder instead.</p>\n"}, {'answer_id': 115305, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 1, 'selected': False, 'text': '<p>I was curious where StringBuilder stood with these tests.  Results below...</p>\n\n<pre><code>class Program {\n   static void Main(string[] args) {\n\n      var p = new { FirstName = "Bill", LastName = "Gates" };\n\n      var tests = new[] {\n         new { Name = "Concat", Action = new Action(delegate() { string x = p.FirstName + " " + p.LastName; }) },\n         new { Name = "Format", Action = new Action(delegate() { string x = string.Format("{0} {1}", p.FirstName, p.LastName); }) },\n         new { Name = "StringBuilder", Action = new Action(delegate() {\n            StringBuilder sb = new StringBuilder();\n            sb.Append(p.FirstName);\n            sb.Append(" ");\n            sb.Append(p.LastName);\n            string x = sb.ToString();\n         }) }\n      };\n\n      var Watch = new Stopwatch();\n      foreach (var t in tests) {\n         for (int i = 0; i &lt; 5; i++) {\n            Watch.Reset();\n            long Elapsed = ElapsedTicks(t.Action, Watch, 10000);\n            Console.WriteLine(string.Format("{0}: {1} ticks", t.Name, Elapsed.ToString()));\n         }\n      }\n   }\n\n   public static long ElapsedTicks(Action ActionDelg, Stopwatch Watch, int Iterations) {\n      Watch.Start();\n      for (int i = 0; i &lt; Iterations; i++) {\n         ActionDelg();\n      }\n      Watch.Stop();\n      return Watch.ElapsedTicks / Iterations;\n   }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre>\nConcat: 406 ticks\nConcat: 356 ticks\nConcat: 411 ticks\nConcat: 299 ticks\nConcat: 266 ticks\nFormat: 5269 ticks\nFormat: 954 ticks\nFormat: 1004 ticks\nFormat: 984 ticks\nFormat: 974 ticks\nStringBuilder: 629 ticks\nStringBuilder: 484 ticks\nStringBuilder: 482 ticks\nStringBuilder: 508 ticks\nStringBuilder: 504 ticks\n</pre>\n'}, {'answer_id': 856794, 'author': 'DonkeyMaster', 'author_id': 5178, 'author_profile': 'https://Stackoverflow.com/users/5178', 'pm_score': 2, 'selected': False, 'text': "<p>I choose based on readability.\nI prefer the format option when there's some text around the variables. In this example:</p>\n<pre><code>Console.WriteLine(&quot;User {0} accessed {1} on {2}.&quot;, \n                   user.Name, fileName, timestamp);\n</code></pre>\n<p>you understand the meaning even without variable names, whereas the concat is cluttered with quotes and + signs and confuses my eyes:</p>\n<pre><code>Console.WriteLine(&quot;User &quot; + user.Name + &quot; accessed &quot; + fileName + \n                  &quot; on &quot; + timestamp + &quot;.&quot;);\n</code></pre>\n<p>(I borrowed Mike's example because I like it)</p>\n<p>If the format string doesn't mean much without variable names, I have to use concat:</p>\n<pre><code>Console.WriteLine(&quot;{0} {1}&quot;, p.FirstName, p.LastName);\n</code></pre>\n<p>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?</p>\n<pre><code>Console.WriteLine(p.FirstName + &quot; &quot; + p.LastName);\n</code></pre>\n<p>Performance-wise, I expect the format option to be slower than the concat, since the format requires the string to be <em>parsed</em>. I don't remember having to optimize this kind of instruction, but if I did, I'd look at <code>string</code> methods like <code>Concat()</code> and <code>Join()</code>.</p>\n<p>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.</p>\n"}, {'answer_id': 962016, 'author': 'Christian Hayter', 'author_id': 115413, 'author_profile': 'https://Stackoverflow.com/users/115413', 'pm_score': 2, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 1082932, 'author': 'Babak Naffas', 'author_id': 120753, 'author_profile': 'https://Stackoverflow.com/users/120753', 'pm_score': 1, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 1822422, 'author': 'Jeremy McGee', 'author_id': 3546, 'author_profile': 'https://Stackoverflow.com/users/3546', 'pm_score': 5, 'selected': False, 'text': "<p><strong>Pity the poor translators</strong></p>\n\n<p>If you <em>know</em> your application will stay in English, then fine, save the clock ticks. However, many cultures would usually see Lastname Firstname in, for instance, addresses. </p>\n\n<p>So use <code>string.Format()</code>, especially if you're going to ever have your application go anywhere that English is not the first language.</p>\n"}, {'answer_id': 13354257, 'author': 'Ludington', 'author_id': 112794, 'author_profile': 'https://Stackoverflow.com/users/112794', 'pm_score': 5, 'selected': False, 'text': '<p>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.</p>\n\n<p>Try this on for size:</p>\n\n<pre><code>Stopwatch s = new Stopwatch();\n\nint n = 1000000;\nlong fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0, sbElapsedMilliseconds = 0, sbElapsedTicks = 0;\n\nRandom random = new Random(DateTime.Now.Millisecond);\n\nstring result;\ns.Start();\nfor (var i = 0; i &lt; n; i++)\n    result = (random.Next().ToString() + " " + random.Next().ToString());\ns.Stop();\ncElapsedMilliseconds = s.ElapsedMilliseconds;\ncElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\ns.Start();\nfor (var i = 0; i &lt; n; i++)\n    result = string.Format("{0} {1}", random.Next().ToString(), random.Next().ToString());\ns.Stop();\nfElapsedMilliseconds = s.ElapsedMilliseconds;\nfElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\nStringBuilder sb = new StringBuilder();\ns.Start();\nfor(var i = 0; i &lt; n; i++){\n    sb.Clear();\n    sb.Append(random.Next().ToString());\n    sb.Append(" ");\n    sb.Append(random.Next().ToString());\n    result = sb.ToString();\n}\ns.Stop();\nsbElapsedMilliseconds = s.ElapsedMilliseconds;\nsbElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\nConsole.WriteLine(n.ToString() + " x result = string.Format(\\"{0} {1}\\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");\nConsole.WriteLine(n.ToString() + " x result = (p.FirstName + \\" \\" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");\nConsole.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");\nConsole.WriteLine("****************");\nConsole.WriteLine("Press Enter to Quit");\nConsole.ReadLine();\n</code></pre>\n\n<p>Sample Output:</p>\n\n<pre><code>1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 513ms - 1499816 ticks\n1000000 x result = (p.FirstName + " " + p.LastName); took: 393ms - 1150148 ticks\n1000000 x sb.Clear();sb.Append(random.Next().ToString()); sb.Append(" "); sb.Append(random.Next().ToString()); result = sb.ToString(); took: 405ms - 1185816 ticks\n</code></pre>\n'}, {'answer_id': 30392913, 'author': 'atlaste', 'author_id': 1031591, 'author_profile': 'https://Stackoverflow.com/users/1031591', 'pm_score': 2, 'selected': False, 'text': "<p>Since I don't think the answers here cover everything, I'd like to make a small addition here.</p>\n<p><code>Console.WriteLine(string format, params object[] pars)</code> calls <code>string.Format</code>. 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.</p>\n<p><strong>Short answer</strong></p>\n<p>The decision you're facing has to do with string allocation. I'll try to make it simple.</p>\n<p>Say you have</p>\n<pre><code>string s = a + &quot;foo&quot; + b;\n</code></pre>\n<p>If you execute this, it will evaluate as follows:</p>\n<pre><code>string tmp1 = a;\nstring tmp2 = &quot;foo&quot; \nstring tmp3 = concat(tmp1, tmp2);\nstring tmp4 = b;\nstring s = concat(tmp3, tmp4);\n</code></pre>\n<p><code>tmp</code> 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 <code>ldstr</code> in IL for literals), you put a reference to a string pointer on the stack.</p>\n<p>The moment you call <code>concat</code> 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.</p>\n<p>Which changes the question to: How can you reduce the number of <code>concat</code> operations?</p>\n<p>So, the rough answer is: <code>string.Format</code> for &gt;1 concats, '+' will work just fine for 1 concat. And if you don't care about doing micro-performance optimizations, <code>string.Format</code> will work just fine in the general case.</p>\n<p><strong>A note about Culture</strong></p>\n<p>And then there's something called culture...</p>\n<p><code>string.Format</code> enables you to use <code>CultureInfo</code> in your formatting. A simple operator '+' uses the current culture.</p>\n<p>This is especially an important remark if you're writing file formats and f.ex. <code>double</code> values that you 'add' to a string. On different machines, you might end up with different strings if you don't use <code>string.Format</code> with an explicit <code>CultureInfo</code>.</p>\n<p>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.</p>\n<p><strong>More detailed answer</strong></p>\n<p>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.</p>\n<p>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.</p>\n<p>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.</p>\n<p><code>StringBuilder</code> is a class that basically over allocates the underlying buffer in powers of two. <code>string.Format</code> uses <code>StringBuilder</code> under the hood.</p>\n<p>This makes your decision a basic trade-off between over-allocate-and-append (-multiple) (w/w.o. culture) or just allocate-and-append.</p>\n"}, {'answer_id': 31888031, 'author': 'Saragis', 'author_id': 2789100, 'author_profile': 'https://Stackoverflow.com/users/2789100', 'pm_score': 3, 'selected': False, 'text': '<p>Starting from C# <code>6.0</code> <a href="https://msdn.microsoft.com/en-us/library/dn961160.aspx" rel="nofollow noreferrer">interpolated strings</a> can be used to do this, which simplifies the format even more.</p>\n<pre><code>var name = &quot;Bill&quot;;\nvar surname = &quot;Gates&quot;;\nMessageBox.Show($&quot;Welcome to the show, {name} {surname}!&quot;);\n</code></pre>\n<blockquote>\n<p>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.</p>\n</blockquote>\n<p>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.</p>\n<p>Please also refer to <a href="http://www.dotnetperls.com/string-interpolation" rel="nofollow noreferrer">this dotnetperls article</a> on string interpolation.</p>\n<p>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).</p>\n'}, {'answer_id': 31955456, 'author': 'von v.', 'author_id': 815073, 'author_profile': 'https://Stackoverflow.com/users/815073', 'pm_score': 3, 'selected': False, 'text': '<p>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. <strong>Better</strong> 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 <a href="https://msdn.microsoft.com/en-us/magazine/dn879355.aspx" rel="noreferrer">C# 6.0</a>:</p>\n\n<pre><code>var p = new { FirstName = "Bill", LastName = "Gates" };\nvar fullname = $"{p.FirstName} {p.LastName}";\n</code></pre>\n\n<p>This new feature is <strong>better</strong>, IMO, and <strong>actually better in our case</strong> 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:</p>\n\n<pre><code>var qs = string.Format("q1={0}&amp;q2={1}&amp;q3={2}&amp;q4={3}&amp;q5={4}&amp;q6={5}", \n    someVar, anotherVarWithLongName, var3, var4, var5, var6)\n</code></pre>\n\n<p>in can be written like this and it\'s easier to read:</p>\n\n<pre><code>var qs=$"q1={someVar}&amp;q2={anotherVarWithLongName}&amp;q3={var3}&amp;q4={var4}&amp;q5={var5}&amp;q6={var6}";\n</code></pre>\n'}, {'answer_id': 68137074, 'author': 'Misha Zaslavsky', 'author_id': 2667173, 'author_profile': 'https://Stackoverflow.com/users/2667173', 'pm_score': 1, 'selected': False, 'text': '<p>The most readable would be to use the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/string-interpolation" rel="nofollow noreferrer">string interpolation</a> feature of C# <code>6.0</code>:</p>\n<pre><code>Console.WriteLine($&quot;{p.FirstName} {p.LastName}&quot;);\n</code></pre>\n<p>Its performance is similar to using &quot;+&quot;.</p>\n'}]
['https://Stackoverflow.com/questions/16432', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/920/']