When do you use StringBuilder.AppendLine/string.Format vs. StringBuilder.AppendFormat?

前端 未结 7 723
半阙折子戏
半阙折子戏 2021-01-31 13:34

A recent question came up about using String.Format(). Part of my answer included a suggestion to use StringBuilder.AppendLine(string.Format(...)). Jon Skeet suggested this was

7条回答
  •  终归单人心
    2021-01-31 14:22

    If performance is important, try to avoid AppendFormat() completely. Use multiple Append() or AppendLine() calls instead. This does make your code larger and less readable, but it's faster because no string parsing has to be done. String parsing is slower than you might imagine.

    I generally use:

    sbuilder.AppendFormat("{0} line", "First");
    sbuilder.AppendLine();
    sbuilder.AppendFormat("{0} line", "Second");
    sbuilder.AppendLine();
    

    Unless performance is critical, in which case I'd use:

    sbuilder.Append("First");
    sbuilder.AppendLine(" line");
    sbuilder.Append("Second");
    sbuilder.AppendLine(" line");
    

    (Of course, this would make more sense if "First" and "Second" where not string literals)

提交回复
热议问题