C#中使用反射的性能分析

字號:

最近在研究一個可配置系統(tǒng)的框架,在代碼中大量使用了反射的方法,雖然借鑒到其他的語言,如Java中反射性能都比較差,但是想到C#既然是一種強類型的語言,對于AppDomain中的類的調(diào)用應該性能不會差很多。
    今天在mvp站點上看到有人說反射的性能很差,要避免使用,就寫了一個簡單的例子測試了一下
    測試類如下:
    namespace ReflectionTest.Test
    {
    public class CTester
    {
    public CTester()
    {
    a = 10;
    }
    public void test1()
    {
    a = (a - 0.0001) * 1.0001;
    }
    private double a;
    public double geta() { return a; }
    }
    }
    首先我們對于對象的構造進行測試
    測試代碼如下
    private void test1()
    {
    label1.Text = "";
    label3.Text = "";
    DateTime now = DateTime.Now;
    for (int i = 0; i < 1000; i++)
    {
    for (int j = 0; j < 100; j++)
    {
    CTester aTest = new CTester();
    }
    }
    TimeSpan spand = DateTime.Now - now;
    label1.Text = "time past " + spand.ToString();
    }
    private void test2()
    {
    label2.Text = "";
    label4.Text = "";
    DateTime now = DateTime.Now;
    for (int i = 0; i < 1000; i++)
    {
    for (int j = 0; j < 100; j++)
    {
    Type theTest = Type.GetType("ReflectionTest.Test.CTester");
    object theobj = theTest.InvokeMember(null, BindingFlags.CreateInstance
    , null, null, null);
    }
    }
    TimeSpan spand = DateTime.Now - now;
    label2.Text = "time past " + spand.ToString();
    }
    測試結果直接調(diào)用的時間為16ms左右,而反射調(diào)用的則始終維持在5s 520ms左右,直接效率比較接近350倍。
    對于這個測試,很有趣的一點是:
    如果將test2中的Type theTest = Type.GetType("ReflectionTest.Test.CTester");
    移到循環(huán)之外,則相應的運行時間下降為1s 332 ms , 效率相差為20倍左右。