String Interpolation vs String.Format

前端 未结 4 888
天命终不由人
天命终不由人 2020-12-02 18:00

Is there a noticable performance difference between using string interpolation:

myString += $\"{x:x2}\";

vs String.Format()?



        
4条回答
  •  不思量自难忘°
    2020-12-02 18:22

    The question was about performance, however the title just says "vs", so I feel like have to add a few more points, some of them are opinionated though.

    • Localization

      • String interpolation cannot be localized due to it's inline code nature. Before localization it has be turned into string.Format. However, there is tooling for that (e.g. ReSharper).
    • Maintainability (my opinion)

      • string.Format is far more readable, as it focuses on the sentence what I'd like to phrase, for example when constructing a nice and meaningful error message. Using the {N} placeholders give me more flexibility and it's easier to modify it later.
      • Also, the inlined format specifier in interploation is easy to misread, and easy to delete together with the expression during a change.
      • When using complex and long expressions, interpolation quickly gets even more hard to read and maintain, so in this sense it doesn't scale well when code is evolving and gets more complex. string.Format is much less prone to this.
      • At the end of the day it's all about separation of concerns: I don't like to mix the how it should present with the what should be presented.

    So based on these I decided to stick with string.Format in most of my code. However, I've prepared an extension method to have a more fluent way of coding which I like much more. The extension's implementaiton is a one-liner, and it looks simply like this in use.

    var myErrorMessage = "Value must be less than {0:0.00} for field {1}".FormatWith(maximum, fieldName);
    

    Interpolation is a great feature, don't get me wrong. But IMO it shines the best in those languages which miss the string.Format-like feature, for example JavaScript.

提交回复
热议问题