String output: format or concat in C#?

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

    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...

    Bill Gates
    Console.WriteLine(p.FirstName + " " + p.LastName); took: 8ms - 30488 ticks
    Bill Gates
    Console.WriteLine("{0} {1}", p.FirstName, p.LastName); took: 0ms - 182 ticks
    

    So the order of the operations makes a HUGE difference, or rather the very first operation is ALWAYS much slower.

    Here is 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:

    Bill Gates
    Console.WriteLine(FirstName + " " + LastName); took: 5ms - 20335 ticks
    Bill Gates
    Console.WriteLine(FirstName + " " + LastName); took: 0ms - 156 ticks
    Bill Gates
    Console.WriteLine(FirstName + " " + LastName); took: 0ms - 122 ticks
    Bill Gates
    Console.WriteLine("{0} {1}", FirstName, LastName); took: 0ms - 181 ticks
    Bill Gates
    Console.WriteLine("{0} {1}", FirstName, LastName); took: 0ms - 122 ticks
    Bill Gates
    String.Concat(FirstName, " ", LastName); took: 0ms - 142 ticks
    Bill Gates
    String.Concat(FirstName, " ", LastName); took: 0ms - 117 ticks
    

    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.

    The initial delay in startup is likely the initialisation of Console Stream, as placing a Console.Writeline("Start!") before the first operation brings all times back into line.

提交回复
热议问题