C#提高性能tips

1,for vs foreach数据结构

2,structure vs class性能

3,property vs dicrect学习

4, array vs list优化

5,Avoid Rethrowing Exceptionsui

6, Refactor your algorithms to rely on hash tablespa

constant time search设计

The absolutely killer
performance collections are hash tables
, implemented through HashSet<T>
and Dictionary<K,V>.  
code

 7, Throw Fewer Exceptionsorm

8, Make Chunky Callsxml

A chunky call is a function call that performs several tasks, such as a method that initializes several fields of an object. 

9, Keep IO Buffer Size Between 4KB and 8KB

10,Be on the Lookout for Asynchronous IO Opportunities

11, 避免没必要要的对象建立 
因为垃圾回收的代价较高,因此C#程序开发要遵循的一个基本原则就是避免没必要要的对象建立。如下列举一些常见的情形。 
11.1 避免循环建立对象 ★ 
若是对象并不会随每次循环而改变状态,那么在循环中反复建立对象将带来性能损耗。高效的作法是将对象提到循环外面建立。 
11.2 在须要逻辑分支中建立对象 
若是对象只在某些逻辑分支中才被用到,那么应只在该逻辑分支中建立对象。 
11.3 使用常量避免建立对象 
程序中不该出现如 new Decimal(0) 之类的代码,这会致使小对象频繁建立及回收,正确的作法是使用Decimal.Zero常量。咱们有设计本身的类时,也能够学习这个设计手法,应用到相似的场景中。 

 12,Dictionary VS List Dictionary和List是最经常使用的两种集合类。选择正确的集合类能够很大的提高程序的性能。为了作出正确的选择,咱们应该对Dictionary和List的各类操做的性能比较了解。 下表中粗略的列出了两种数据结构的性能比较。 

 

操做

List

Dictionary

索引

Find(Contains)

Add

Insert

Remove

 

13,TryGetValue 对于Dictionary的取值,比较直接的方法是以下代码: 

if(_dic.ContainKey("Key")
{
return _dic\["Key"\];
}

当须要大量取值的时候,这样的取法会带来性能问题。优化方法以下:

object value;
if(_dic.TryGetValue("Key", out value))
{
return value;
}

使用TryGetValue能够比先Contain再取值提升一倍的性能。

14,若是只是从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+ ",";  
}
15, 避免使用递归调用和嵌套循环,使用他们会严重影响性能,在不得不用的时候才使用。
16 , sealed

http://codebetter.com/patricksmacchia/2009/04/19/micro-optimization-tips-to-increase-performance/

https://msdn.microsoft.com/en-us/library/ms973839.aspx

https://blogs.msdn.microsoft.com/ricom/2006/03/09/performance-quiz-9-ilistlttgt-list-and-array-speed/

https://msdn.microsoft.com/zh-cn/library/ms973858.aspx

https://blogs.msdn.microsoft.com/vancem/

https://zhuanlan.zhihu.com/p/28471848

相关文章
相关标签/搜索