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

前端 未结 7 719
半阙折子戏
半阙折子戏 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:12

    String.format creates a StringBuilder object internally. By doing

    sbuilder.AppendLine( String.Format( "{0} line", "First"));
    

    an additional instance of string builder, with all of its overhead is created.


    Reflector on mscorlib, Commonlauageruntimelibary, System.String.Format

    public static string Format(IFormatProvider provider, string format, params object[] args)
    {
        if ((format == null) || (args == null))
        {
            throw new ArgumentNullException((format == null) ? "format" : "args");
        }
        StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
        builder.AppendFormat(provider, format, args);
        return builder.ToString();
    }
    

提交回复
热议问题