撰写高效率的.NET程序
来源:互联网 发布:中国和美国的差距知乎 编辑:程序博客网 时间:2024/05/02 01:09
撰写高效率的.NET程序 1)避免使用ArrayList。 2)使用HashTale代替其他字典集合类型(如StringDictionary,NameValueCollection,HybridCollection),存放少量数据的时候可以使用HashTable. 3)为字符串容器声明常量,不要直接把字符封装在双引号" "里面。 //推荐 4) 不要用UpperCase,Lowercase转换字符串进行比较,用String.Compare代替,它可以忽略大小写进行比较. //避免 //推荐 6) If you are only reading from the XML object, avoid using XMLDocumentt, instead use XPathDocument, which is readonly and so improves performance. . //推荐 //避免 } //推荐 8) 捕获指定的异常,不要使用通用的System.Exception. //避免 9) 使用Try...catch...finally时, 要在finally里释放占用的资源如连接,文件流等 谁都会写代码!几个月的编程经验可以让你写出“可运行应用程序”。让它可运行容易,但是以最有效率的方式编码就需要下更多的功夫!
影响.NET执行效率的因素
1. 虚拟堆栈机器
2. 垃圾回收器
3. 即时编译器JIT
4. 最优化机器编译器
5. 正确使用.NET机制和.NET Freamwork
掌握虚拟堆栈机器
小心使用,不要滥用。不要在方法或函数中声明太多太大的局部变
量。不要多于64个局部变量。不要用1个大方法。
垃圾回收器
除非开发人员知道自己做什么,要尽量避免干扰垃圾回收器的工作,不要撰写太大的对象。
在多CPU上<configuration><runtime><gcConcurrent enabled="false"/></runtime></configuration>
即时编译器JIT
写类方法时避免大方法。
最优化机器编译器
使用内联展开可以有效地在使用许多小型函数应用程序中增加执行效率
如果方法有如下特性不会成为内联展开方法
1. 虚方法
2. 大于32个字节的IL方法
3. 复杂控制流程的方法
4. 使用try catch
5. 拥有结构Structs参数或是声明结构区域变量的方法
foreach
有可能产生缓慢的执行程序代码。
string
string对象的内容是不可以改变的,如果做串联会造成许多临时字符串对象的创建和释放,很缓慢。要用StringBuilder。
Collection类
最好建立一个适合应用程序适用的体积大小,即不要一定用不带参数的形式。
引用型和值类型
值类型在堆栈上配置,免除动态建立和释放,也可以避免垃圾回收器过度的启动。
小心使用Reflection
Reflection很好也很昂贵,要避免在瓶颈或者经常执行的地方用反射。
建议
避免滥用XML,昂贵,缓慢。
避免滥用Exception。
只在需要才引入Assembly。
多线程中尽量用ThreadPool比Thread效率更好。
在多cpu机器中使用服务器端垃圾回收器,使用异步调用用以增加.NET程序反应时间。
优化 .NET的性能
因为任何对象添加到ArrayList都要封箱为System.Object类型,从ArrayList取出数据时,要拆箱回实际的类型。建议使用自定义 的集合类型代替ArrayList。.net 2.0提供了一个新的类型,叫泛型,这是一个强类型,使用泛型集合就可以避免了封箱和拆箱的发生,提高了性能。
//避免
//
MyObject obj = new MyObject();
obj.Status = "ACTIVE";
const string C_STATUS = "ACTIVE";
MyObject obj = new MyObject();
obj.Status = C_STATUS;
例:
const string C_VALUE = "COMPARE";
if (String.Compare(sVariable, C_VALUE, true) == 0)
{
Console.Write("SAME");
}
5) 用StringBuilder代替使用字符串连接符 “+”,.
String sXML = "<parent>";
sXML += "<child>";
sXML += "Data";
sXML += "</child>";
sXML += "</parent>";
StringBuilder sbXML = new StringBuilder();
sbXML.Append("<parent>");
sbXML.Append("<child>");
sbXML.Append("Data");
sbXML.Append("</child>");
sbXML.Append("</parent>");
如果只是从XML对象读取数据,用只读的XPathDocument代替XMLDocument,可以提高性能
//避免
XmlDocument xmld = new XmlDocument();
xmld.LoadXml(sXML);
txtName.Text = xmld.SelectSingleNode("/packet/child").InnerText;
XPathDocument xmldContext = new XPathDocument(new StringReader(oContext.Value));
XPathNavigator xnav = xmldContext.CreateNavigator();
XPathNodeIterator xpNodeIter = xnav.Select("packet/child");
iCount = xpNodeIter.Count;
xpNodeIter = xnav.SelectDescendants(XPathNodeType.Element, false);
while(xpNodeIter.MoveNext())
{
sCurrValues += xpNodeIter.Current.Value+"~";
}
7) 避免在循环体里声明变量,应该在循环体外声明变量,在循环体里初始化。
for(int i=0; i<10; i++)
{
SomeClass objSC = new SomeClass();
.
.
.
SomeClass objSC = null;
for(int i=0; i<10; i++)
{
objSC = new SomeClass();
.
.
.
}
try
{
<some logic>
}
catch(Exception exc)
{
<Error handling>
}
//推荐
try
{
<some logic>
}
catch(System.NullReferenceException exc)
{
<Error handling>
}
catch(System.ArgumentOutOfRangeException exc)
{
<Error handling>
}
catch(System.InvalidCastException exc)
{
<Error handling>
}
不然在Catch到错误后占用的资源不能释放。
try
{
...
}
catch
{...}
finally
{
conntion.close()
}
10) 避免使用递归调用和嵌套循环,使用他们会严重影响性能,在不得不用的时候才使用。
C# 编码规范和编程好习惯
要知道,大多数程序员在写”可运行代码,“而不是”高效代码“。我们在这个指南课程前面提到,你想成为你们公司”最尊贵的专业人员“吗?写”高效代码“是一项艺术,你必须学习和实践它。命名惯例和规范
注记 :
Pascal 大小写形式-所有单词第一个字母大写,其他字母小写。
Camel 大小写形式-除了第一个单词,所有单词第一个字母大写,其他字母小写。public class HelloWorld{ ...}
public class HelloWorld{ void SayHello(string name) { ... }}
public class HelloWorld{ int totalCount = 0; void SayHello(string name) { string fullMessage = "Hello " + name; ... }}
以前,多数程序员喜欢它-把数据类型作为变量名的前缀而m_作为成员变量的前缀。例如:string m_sName;int nAge;
然而,这种方式在.NET编码规范中是不推荐的。所有变量都用camel 大小写形式,而不是用数据类型和m_来作前缀。
- 别用缩写。用name, address, salary等代替 nam, addr, sal
- 别使用单个字母的变量象i, n, x 等. 使用 index, temp等
用于循环迭代的变量例外:for ( int i = 0; i < count; i++ ){ ...}
如果变量只用于迭代计数,没有在循环的其他地方出现,许多人还是喜欢用单个字母的变量(i) ,而不是另外取名。
- 变量名中不使用下划线 (_) 。
- 命名空间需按照标准的模式命名.
..
例如,对于类HelloWorld, 相应的文件名应为 helloworld.cs (或, helloworld.vb)缩进和间隔
bool SayHello (string name) { string fullMessage = "Hello " + name; DateTime currentTime = DateTime.Now; string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString(); MessageBox.Show ( message ); if ( ... ) { // Do something // ... return false; } return true; }
这段代码看起来比上面的好::bool SayHello ( string name ) { string fullMessage = "Hello " + name; DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
if ( ... ) { // Do something // ...
return false; }
return true; }
好:if ( ... ) { // Do something }
不好:if ( ... ) { // Do something }
好:if ( showResult == true ) { for ( int i = 0; i < 10; i++ ) { // } }
不好:if(showResult==true) { for(int i= 0;i<10;i++) { // } }
良好的编程习惯
遵从以下良好的习惯以写出好程序
好:void SavePhoneNumber ( string phoneNumber ) { // Save the phone number. }
不好:// This method will save the phone number. void SaveData ( string phoneNumber ) { // Save the phone number. }
好:// Save the address. SaveAddress ( address ); // Send an email to the supervisor to inform that the address is updated. SendEmail ( address, email ); void SaveAddress ( string address ) { // Save the address. // ... } void SendEmail ( string address, string email ) { // Send an email to inform the supervisor that the address is changed. // ... }
不好:// Save address and send an email to the supervisor to inform that the address is updated. SaveAddress ( address, email ); void SaveAddress ( string address, string email ) { // Job 1. // Save the address. // ... // Job 2. // Send an email to inform the supervisor that the address is changed. // ... }
好:int age; string name; object contactInfo;
不好:Int16 age; String name; Object contactInfo;
好:enum MailType { Html, PlainText, Attachment } void SendMail (string message, MailType mailType) { switch ( mailType ) { case MailType.Html: // Do something break; case MailType.PlainText: // Do something break; case MailType.Attachment: // Do something break; default: // Do something break; } }
不好:void SendMail (string message, string mailType) { switch ( mailType ) { case "Html": // Do something break; case "PlainText": // Do something break; case "Attachment": // Do something break; default: // Do something break; } }
注释
异常处理
好:void ReadFromFile ( string fileName ) { try { // read from file. } catch (FileIOException ex) { // log error. // re-throw exception depending on your case. throw; } }
不好:void ReadFromFile ( string fileName ) { try { // read from file. } catch (Exception ex) { // Catching general exception is bad... we will never know whether it // was a file error or some other error. // Here you are hiding an exception. // In this case no one will ever know that an exception happened. return ""; } }
- 撰写高效率的.NET程序
- 撰写高效率的.NET程序
- 做个高效率的程序猿,使用VS内置的ASP.NET Web 服务器调试
- 经典面试程序前言-简历的撰写
- AjaxPro.NET框架生成高效率的Tree
- 写高效率程序需要的知识
- Smarty 程序撰写步骤
- ASP.NET撰写的物流合同管理平台
- 撰写易维护易扩展的数据库程序Delphi篇
- 高效率嵌入式程序开发
- 高效率嵌入式程序开发
- 高效率嵌入式程序开发
- 高效率嵌入式程序开发
- 高效率嵌入式程序开发
- 高效率嵌入式程序开发
- 高效率嵌入式程序开发
- 用 VB 来开发高效率的底层程序
- 关于新手程序撰写风格
- 经典的多图切换效果 JS版
- 开始新版梭织CAD底层数据COM组件的封装(2007-03-15)
- 关闭浏览器
- JSON -- 轻量级的数据交换语言
- cURL/libcURL HTTP Location:重新定向绕过安全限制漏洞
- 撰写高效率的.NET程序
- EVC绘制位图--BeginPaint()与GetDC()的区别
- 中途插入其它工作(2007-03-26)
- ArcObject API 开发(一)
- 转:MOSS 2007 Filter webparts ,建立筛选Document Library 的Web Part
- N76 UCWEB 6.7免费下载
- SQL CE 3.5 部署打包的问题
- 筛选法求100以内的素数
- Java:内部非静态类访问外部类成员的方法