String output: format or concat in C#?

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

    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.

    Using the following code:

        System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
    
        var p = new { FirstName = "Bill", LastName = "Gates" };
    
        s.Start();
        Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
        s.Stop();
        Console.WriteLine("Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName); took: " + s.ElapsedMilliseconds + "ms - " + s.ElapsedTicks + " ticks");
    
        s.Reset();
        s.Start();
        Console.WriteLine(p.FirstName + " " + p.LastName);
        s.Stop();
    
        Console.WriteLine("Console.WriteLine(p.FirstName + \" \" + p.LastName); took: " + s.ElapsedMilliseconds + "ms - " + s.ElapsedTicks + " ticks");
    

    I got the following results:

    Bill Gates
    Console.WriteLine("{0} {1}", p.FirstName, p.LastName); took: 2ms - 7280 ticks
    Bill Gates
    Console.WriteLine(p.FirstName + " " + p.LastName); took: 0ms - 67 ticks
    

    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.

提交回复
热议问题