摘要:利用Stopwatch來測試string與StringBuilder做字串相加的效能
如果用c#寫程式要測試效能..可以利用Stopwatch來計算程式的執行時間...
可以參考這篇"利用 Stopwatch 類別來測試 Parse() 與 TryParse()"
小弟就拿string與StringBuilder來比較兩者在做字串相加...看那一個效能會比較好..
注意:
要使用Stopwatch必需using System.Diagnostics;
要使用StringBuilder必需using System.Text;
asp.net(c#)
Test.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="次數:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="執行" /></div>
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="次數:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="執行" /></div>
</form>
</body>
</html>
Test.aspx.cs
























Stopwatch sw2 = new Stopwatch();

sw2.Start();








Response.Write("<br/>測試使用string累加文字所需時間:" + sw2.ElapsedTicks.ToString() + "<br/><br/>");






Stopwatch sw1 = new Stopwatch();

sw1.Start();








Response.Write("<br/>測試使用StringBuilder累加文字所需時間:" + sw1.ElapsedTicks.ToString() + "<br/><br/>");



執行結果:
結論:使用StringBuilder做字串相加會比string效能好很多
參考網址:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
http://www.cnblogs.com/allenlooplee/archive/2005/08/16/216398.html
http://www.dotblogs.com.tw/chhuang/archive/2008/03/18/1779.aspx