需要通过ASP.NET MVC生成一个列表,MVC里面根正苗红的HTML生成方式是使用TagBuilder,鉴于性能的需求,对TagBuilder进行了一番性能测试.当然测试需要比较,所以采用三种方式来进行性能测试
(1):TagBuilder的方式
(2):格式化字符串的方式(string.Format)
(3):HtmlTextWriter的方式
测试使用的性能工具是老赵贡献的CodeTimer(有兴趣的可以去老赵的博客上找),感谢一下先.
测试代码如下:
Codeclass Program
{
static void Main(string[] args)
{
string result1;
string result2;
string result3;
// 先热身
CodeTimer.Initialize();
// 针对TagBuilder的性能测试
CodeTimer.Time("TagBuilder", 1000, () =>
{
StringBuilder sb = new StringBuilder();
TagBuilderTest(sb);
result1 = sb.ToString();
});
// 针对string.format的性能测试
CodeTimer.Time("String.Format", 1000, () =>
{
StringBuilder sb = new StringBuilder();
StringFormatTest(sb);
result2 = sb.ToString();
});
// 针对HtmlTextWriter的性能测试
CodeTimer.Time("HtmlTextWriter", 1000, () =>
{
HtmlTextWriter writer = new HtmlTextWriter(new StringWriter());
HtmlWriter(writer);
result3 = writer.InnerWriter.ToString();
});
}
static void TagBuilderTest(StringBuilder sb)
{
for (var i = 0; i < 1000; i++)
{
TagBuilder tag = new TagBuilder("div");
tag.Attributes["id"] = "id1";
tag.Attributes["title"] = "google?";
tag.InnerHtml = "goo~~gle";
sb.Append(tag.ToString());
}
}
static void StringFormatTest(StringBuilder sb)
{
for (var i = 0; i < 1000; i++)
{
sb.Append(
string.Format(@"<div id=""{0}"" title=""{1}"">{2}</div>", "id1", "google?", "goo~~gle")
);
}
}
static void HtmlWriter(HtmlTextWriter writer)
{
for (var i = 0; i < 1000; i++)
{
writer.AddAttribute(HtmlTextWriterAttribute.Id, "id1");
writer.AddAttribute(HtmlTextWriterAttribute.Title, "google?");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
writer.Write("goo~~gle");
writer.RenderEndTag();
}
}
}
第一次测试结果:
第二次测试结果:
发现测试的数据很稳定,String.Format性能最快,其次是HtmlTextWriter,最次是TagBuilder.鉴于StringFormat不容易修改和没有结构行,决定采用HtmlTextWriter的形式.
觉得TagBuilder可能比较适用于简单的单个标签的生成,毕竟不像HtmlTextWriter那样需要一个TextWriter.