用 StringBuilder 类替代 String
2024-07-21 02:16:50
供稿:网友
在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秒,效率提高太多了.国内最大的酷站演示中心!