用 StringBuilder 类替代 String

<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 728x15, 创建于 08-4-23MSDN */ google_ad_slot = "3624277373"; google_ad_width = 728; google_ad_height = 15; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 160x600, 创建于 08-4-23MSDN */ google_ad_slot = "4367022601"; google_ad_width = 160; google_ad_height = 600; //--> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
在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
11AJ53500P53934.jpg
seover="window.status='正文--用 StringBuilder 类替代 String';return true">
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 728x15, 创建于 08-4-23MSDN */ google_ad_slot = "3624277373"; google_ad_width = 728; google_ad_height = 15; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 160x600, 创建于 08-4-23MSDN */ google_ad_slot = "4367022601"; google_ad_width = 160; google_ad_height = 600; //--> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
阅读更多
个人分类: .net
想对作者说点什么? 我来说一句

StringStringBuilder类的区别

2008年10月18日 650B 下载

格式化字符串的一些基本讲解

2010年04月23日 103KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭