<%@ Page Language="C#" %> <script runat="server"> void Page_Load(Object Source, EventArgs E) { int intLimit = 10000; DateTime startTime; DateTime endTime; TimeSpan elapsedTime; string strSub; string strWhole = ""; // 首先执行字符串连接操作 startTime = DateTime.Now; for (int i=0; i < intLimit; i++) { strSub = i.ToString(); strWhole = strWhole + " " + strSub; } endTime = DateTime.Now; elapsedTime = endTime - startTime; lblConcat.Text = elapsedTime.ToString(); // lblConcatString.Text = strWhole; // 使用stringBuilder类进行同样的操作 startTime = DateTime.Now; StringBuilder sb = new StringBuilder(); for (int i=0; i < intLimit; i++) { strSub = i.ToString(); sb.Append(" "); sb.Append(strSub); } endTime = DateTime.Now; elapsedTime = endTime - startTime; lblBuild.Text = elapsedTime.ToString(); // lblBuildString.Text = sb.ToString(); } </script> <html> <body> <form runat="server"> <h1>String Concatenation Benchmark</h1> Concatenation: <asp:Label id="lblConcat" runat="server"/> <br/> <asp:Label id="lblConcatString" runat="server"/> <br/> <br/> StringBuilder: <asp:Label id="lblBuild" runat="server"/> <br/> <asp:Label id="lblBuildString" runat="server"/> </form> </body> </html>
|