所有的應用程序都應該遵守的
這里的列舉的是所有的應用程序都可以用來提高性能的一些小建議:
盡早地拋出例外:Throw Exception
Exception是非常地消耗的,你可以數一下你的程序里面有多少個Exception,你看了之后就會大吃驚,注意,不要忘了,一些系統自己的方法也會拋出Exception的,比如,IO類。下面的程序你可以試一下,它用的是一個For循環,你運行后就會發現Exception原來如此可怕。
public static void Main(string[] args){
int j = 0;
for(int i = 0; i < 10000; i++){
try{
j = i;
throw new System.Exception();
} catch {}
}
System.Console.Write(j);
return;
}
要多一些多功能函數
盡量避免一個函數只完成非常小的一個或幾個功能,因為這樣會使系統調用函數過于頻繁,而導致性能的下降。我們應當在盡可能分割功能情況下,合并一些功能,使一個函數能完成多個功能,使函數調用次數減少,以提高效率。
用值類型進行工作
當數據結構比較簡單時,請使用值類型的struct來取代class,這樣會獲得性能的提升。下面的例子說明了這一點:
public struct foo{
public foo(double arg){ this.y = arg; }
public double y;
}
public class bar{
public bar(double arg){ this.y = arg; }
public double y;
}
class Class1{
static void Main(string[] args){
System.Console.WriteLine("starting struct loop...");
for(int i = 0; i < 50000000; i++)
{foo test = new foo(3.14);}
System.Console.WriteLine("struct loop complete.
starting object loop...");
for(int i = 0; i < 50000000; i++)
{bar test2 = new bar(3.14); }
System.Console.WriteLine("All done");
}
}
}
運行程序,你將發現struct的循環比class的要快得多。但使用struct時要小心,因為它并不是在什么時候都是這么快。
在群體操作時使用AddRange取代Add
這也是一個重要的技術,用AddRange可以讓我們要加入的東西一次性加入,而不要每次都加一次,這樣顯然可以加快速度。幾乎所有的windows control都支持Add和AddRange兩種方法。
下面列出了支持Add和AddRange的類:
StringCollection, TraceCollection, etc.
HttpWebRequest
UserControl
ColumnHeader
去除工作中的不要的東西
去除你的項目中的沒有必要的Assemblies,因為它會降低你的程序的性能。想一想,如果你把所有的assemblies都引用進來,為的只是一個方法,是不是得小于失,所以,把沒有用到的assembly都拿走。
文章來源于領測軟件測試網 http://www.kjueaiud.com/