String output: format or concat in C#?

前端 未结 30 1668
一生所求
一生所求 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: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
    

提交回复
热议问题