String output: format or concat in C#?

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

    Generally I prefer the former, as especially when the strings get long it can be much easier to read.

    The other benefit is I believe one of performance, as the latter actually performs 2 string creation statements before passing the final string to the Console.Write method. String.Format uses a StringBuilder under the covers I believe, so multiple concatenations are avoided.

    It should be noted however that if the parameters you are passing in to String.Format (and other such methods like Console.Write) are value types then they will be boxed before passed in, which can provide its own performance hits. Blog post on this here.

提交回复
热议问题