String output: format or concat in C#?

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

    I actually like the first one because when there are a lot of variables intermingled with the text it seems easier to read to me. Plus, it is easier to deal with quotes when using the string.Format(), uh, format. Here is decent analysis of string concatenation.

    0 讨论(0)
  • 2020-11-22 12:03

    Try this code.

    It's a slightly modified version of your code.
    1. I removed Console.WriteLine as it's probably few orders of magnitude slower than what I'm trying to measure.
    2. I'm starting the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute.
    3. The way you divided the result by some iterations was wrong. See what happens if you have 1000 milliseconds and 100 milliseconds. In both situations, you will get 0 ms after dividing it by 1000000.

    Stopwatch s = new Stopwatch();
    
    var p = new { FirstName = "Bill", LastName = "Gates" };
    
    int n = 1000000;
    long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;
    
    string result;
    s.Start();
    for (var i = 0; i < n; i++)
        result = (p.FirstName + " " + p.LastName);
    s.Stop();
    cElapsedMilliseconds = s.ElapsedMilliseconds;
    cElapsedTicks = s.ElapsedTicks;
    s.Reset();
    s.Start();
    for (var i = 0; i < n; i++)
        result = string.Format("{0} {1}", p.FirstName, p.LastName);
    s.Stop();
    fElapsedMilliseconds = s.ElapsedMilliseconds;
    fElapsedTicks = s.ElapsedTicks;
    s.Reset();
    
    
    Console.Clear();
    Console.WriteLine(n.ToString()+" x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");
    Console.WriteLine(n.ToString() + " x result = (p.FirstName + \" \" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");
    Thread.Sleep(4000);
    

    Those are my results:

    1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 618ms - 2213706 ticks
    1000000 x result = (p.FirstName + " " + p.LastName); took: 166ms - 595610 ticks

    0 讨论(0)
  • 2020-11-22 12:04

    I'd use the String.Format, but I would also have the format string in the resource files so it can be localised for other languages. Using a simple string concat doesn't allow you to do that. Obviously if you wont ever need to localise that string, this isn't a reason to think about. It really depends on what the string is for.

    If it's going to be showed to the user, I'd use String.Format so I can localize if I need to - and FxCop will spell check it for me, just in case :)

    If it contains numbers or any other non-string things (e.g. dates), I'd use String.Format because it gives me more control over the formatting.

    If it's for building a query like SQL, I'd use Linq.

    If for concatenating strings inside a loop, I'd use StringBuilder to avoid performance problems.

    If it's for some output the user wont see, and isn't going to effect performance I'd use String.Format because I'm in the habit of using it anyway and I'm just used to it :)

    0 讨论(0)
  • 2020-11-22 12:06

    I've always gone the string.Format() route. Being able to store formats in variables like Nathan's example is a great advantage. In some cases I may append a variable but once more than 1 variable is being concatenated I refactor to use formatting.

    0 讨论(0)
  • 2020-11-22 12:11

    For very simple manipulation I'd use concatenation, but once you get beyond 2 or 3 elements Format becomes more appropriate IMO.

    Another reason to prefer String.Format is that .NET strings are immutable and doing it this way creates fewer temporary/intermediate copies.

    0 讨论(0)
  • 2020-11-22 12:11

    I think this depends heavily on how complex the output is. I tend to choose whichever scenario works best at the time.

    Pick the right tool based on the job :D Whichever looks cleanest!

    0 讨论(0)
提交回复
热议问题