日期:2013-09-19  浏览次数:20472 次

在ASP.NET中我们经常要用到文本对象,一般的操作是定义一个string mystr,然后用mystr+="aaaa"之类的运算来累加.其实还有一个效率高得多的方法:使用 System.Text.StringBuilder 类,该类提供了更高的性能.
举例:我们通常会这么写:
String begin_query = "select UPPER(MachineName) As MachineName, "+"LOWER(MachineOwner) As MachineOwner, Status, "+ "StartTime from NET_STRESS WHERE ";
String end_query = " AND StartTime > '" + startTime + "'AND StartTime < '" + endTime + "'";
String query = begin_query + GetWhereClause("PASSED") + end_query;


用StringBuilder类这么写:

StringBuilder begin_query = new StringBuilder();
begin_query.Append("select UPPER(MachineName) As MachineName ");
begin_query.Append("LOWER(MachineOwner) As MachineOwner, Status, ");
begin_query.Append("StartTime from NET_STRESS WHERE ");

StringBuilder end_query = new StringBuilder();
end_query.Append(" AND StartTime > '");
end_query.Append(startTime);
end_query.Append("' AND StartTime < '");
end_query.Append(endTime);
end_query.Append("'");

String query = begin_query.Append(GetWhereClause("PASSED")).Append(end_query).ToString();

其实这个例子中性能的提高有限,毕竟串长度很短,阿猫写的一个程序需要动态生成大约500K的报表页面,用STRING需要40-60秒,用StringBuilder只需<10秒,效率提高太多了.