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

相關文章
相關標籤/搜索