1)避免使用ArrayList。
因为任何对象添加到ArrayList都要封箱为System.Object类型,从ArrayList取出数据时,要拆箱回实际的类型。建议使用自定义的集合类型代替ArrayList。.net 2.0提供了一个新的类型,叫泛型,这是一个强类型,使用泛型集合就可以避免了封箱和拆箱的发生,提高了性能。
2)使用HashTale代替其他字典集合类型(如StringDictionary,NameValueCollection,HybridCollection),存放少量数据的时候可以使用HashTable.
3)为字符串容器声明常量,不要直接把字符封装在双引号" "里面。
//避免 // 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"); } |
//避免 String sXML = " sXML += " sXML += "Data"; sXML += ""; sXML += ""; //推荐 StringBuilder sbXML = new StringBuilder(); sbXML.Append(" sbXML.Append(" sbXML.Append("Data"); sbXML.Append(""); sbXML.Append(""); |
6) If you are only reading from the XML object, avoid using XMLDocumentt, instead use XPathDocument, which is readonly and so improves performance.
如果只是从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+"~"; } |