StringBuilder 與 String 運行於動態字串串接效能測試測試環境- OS:Windows 7 64bit
- IDE:Visual Studio 2010
- Project Type:Web From Developer
- Framework: ASP.NET 4
MSDN StringBuilder官方說明引用:
測試範例碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//StringBuilder namespace
using System.Text;
//StopWatch namespace
using System.Diagnostics;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string sg = "";
StringBuilder sb = new StringBuilder();
//程序計時器
Stopwatch sw = new Stopwatch();
//loop count 一萬次
int count = 10000;
//計時器開始計時
sw.Start();
for (int i = 0; i < count; i++)
{
//如同 s += (i + abcdefghijklmnopqrstuvwxyz);
sb.Append(i);
sb.Append("abcdefghijklmnopqrstuvwxyz");
}
//計時器中止
sw.Stop();
//輸出到瀏覽器上,</br是瀏覽器上的斷行>
//1ms = 0.001秒
Response.Write ("StringBuilder執行時間" + sw.ElapsedMilliseconds + "ms" + "</br>");
//計時器重置
sw.Reset();
sw.Start();
for (int j = 0; j < count; j++)
{
sg += j + "abcdefghijklmnopqrstuvwxyz";
}
sw.Stop();
Response.Write("String執行時間" + sw.ElapsedMilliseconds + "ms" + "</br>");
}
}
輸出結果:
StringBuilder執行時間6ms
String執行時間5108ms
備註:
- 但是要注意,若是固定格式的靜態字串,使用StringBuilder反而效能會變差。
參考資料: