String output: format or concat in C#?

前端 未结 30 1654
一生所求
一生所求 2020-11-22 11:40

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 = \"Ga

相关标签:
30条回答
  • 2020-11-22 11:48

    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.

    0 讨论(0)
  • 2020-11-22 11:49

    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);
    
    0 讨论(0)
  • 2020-11-22 11:49

    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
    
    0 讨论(0)
  • 2020-11-22 11:52

    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, are more memory efficient.

    What is so bad about string concatenation?

    0 讨论(0)
  • 2020-11-22 11:52

    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.

    0 讨论(0)
  • 2020-11-22 11:52

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

    0 讨论(0)
提交回复
热议问题