当你用StringBuilder.AppendLine/string.格式与StringBuilder.AppendFormat?
-
20-08-2019 - |
题
最近的一次 问题来了 关于使用串。格式().部分的我的答案包括一个建议使用StringBuilder.AppendLine(string.格式(...)).Jon双向飞碟建议,这是一个不好的例子,并提议使用一个组合AppendLine和AppendFormat.
它发生在我身上我从来没有真正解决自己变成一个"优先"的方式使用这些方法。我想我可能开始使用类似于以下,但我想知道什么其他的人用作一个"最佳做法":
sbuilder.AppendFormat("{0} line", "First").AppendLine();
sbuilder.AppendFormat("{0} line", "Second").AppendLine();
// as opposed to:
sbuilder.AppendLine( String.Format( "{0} line", "First"));
sbuilder.AppendLine( String.Format( "{0} line", "Second"));
解决方案
我查看AppendFormat
随后AppendLine
作为不仅更加可读,但也比调用AppendLine(string.Format(...))
更好的性能。
,后者产生一个全新的字符串,然后批发它附加到现有的助洗剂。我不打算去尽可能说:“何必使用StringBuilder的呢?”但它确实似乎对StringBuilder的精神一点。
其他提示
只是创建一个扩展的方法。
public static StringBuilder AppendLine(this StringBuilder builder, string format, params object[] args)
{
builder.AppendFormat(format, args).AppendLine();
return builder;
}
原因我喜欢这样的:
- 不遭受多的开销
AppendLine(string.Format(...))
, 如上所述。 - 防止我忘记加入
.AppendLine()
部分末尾(经常发生足够的). - 更具可读性(但这更多的是一个意见).
如果你不喜欢它被称为'AppendLine,'你可以改变它AppendFormattedLine'或任何你想要的。我享受一切衬上其他调用'AppendLine':
var builder = new StringBuilder();
builder
.AppendLine("This is a test.")
.AppendLine("This is a {0}.", "test");
只是添加一些为每个超载使用的AppendFormat方法上StringBuilder.
的String.format内部创建一个StringBuilder对象。通过这样做
sbuilder.AppendLine( String.Format( "{0} line", "First"));
字符串生成器的其他实例,其所有的开销被创建。
上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();
}
如果性能是很重要的,尽量避免AppendFormat()完全。使用多个附加()或AppendLine()调用来代替。这确实让你的代码更大的可读性,但由于没有字符串解析必须完成它的速度更快。字符串解析慢比你想象。
我一般使用:
sbuilder.AppendFormat("{0} line", "First");
sbuilder.AppendLine();
sbuilder.AppendFormat("{0} line", "Second");
sbuilder.AppendLine();
除非性能是至关重要的,在这种情况下,我使用:
sbuilder.Append("First");
sbuilder.AppendLine(" line");
sbuilder.Append("Second");
sbuilder.AppendLine(" line");
(当然,这会更有意义,如果“第一”和“第二”,其中不字符串文字)
AppendFormat()是一个很多比AppendLine更可读的(的String.Format())
我喜欢这个结构:
sbuilder.AppendFormat("{0} line\n", "First");
虽然公认有一些用于分离出换行可说
时,它只是正可怕简单地使用
sbuilder.AppendFormat("{0} line\n", first);
?我的意思是,我知道这不是平台无关的或什么,但在9个10情况下,它能够完成任务。