String output: format or concat in C#?

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

    Here are my results over 100,000 iterations:

    Console.WriteLine("{0} {1}", p.FirstName, p.LastName); took (avg): 0ms - 689 ticks
    Console.WriteLine(p.FirstName + " " + p.LastName); took (avg): 0ms - 683 ticks
    

    And here is the bench code:

    Stopwatch s = new Stopwatch();
    
    var p = new { FirstName = "Bill", LastName = "Gates" };
    
    //First print to remove the initial cost
    Console.WriteLine(p.FirstName + " " + p.LastName);
    Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
    
    int n = 100000;
    long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;
    
    for (var i = 0; i < n; i++)
    {
        s.Start();
        Console.WriteLine(p.FirstName + " " + p.LastName);
        s.Stop();
        cElapsedMilliseconds += s.ElapsedMilliseconds;
        cElapsedTicks += s.ElapsedTicks;
        s.Reset();
        s.Start();
        Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
        s.Stop();
        fElapsedMilliseconds += s.ElapsedMilliseconds;
        fElapsedTicks += s.ElapsedTicks;
        s.Reset();
    }
    
    Console.Clear();
    
    Console.WriteLine("Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName); took (avg): " + (fElapsedMilliseconds / n) + "ms - " + (fElapsedTicks / n) + " ticks");
    Console.WriteLine("Console.WriteLine(p.FirstName + \" \" + p.LastName); took (avg): " + (cElapsedMilliseconds / n) + "ms - " + (cElapsedTicks / n) + " ticks");
    

    So, I don't know whose reply to mark as an answer :)

提交回复
热议问题