技术开发 频道

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

IT168 技术开发】

    最近在研究一个可配置系统的框架,在代码中大量使用了反射的方法,虽然借鉴到其他的语言,如java中反射性能都比较差,但是想到c#既然是一种强类型的语言,对于AppDomain中的类的调用应该性能不会差很多。

    今天在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(); }

    测试结果直接调用的时间为16ms左右,而反射调用的则始终维持在5s 520ms左右,直接效率比较接近350倍。对于这个测试,很有趣的一点是:
    如果将test2中的Type theTest = Type.GetType("ReflectionTest.Test.CTester");

    移到循环之外,则相应的运行时间下降为1s 332 ms , 效率相差为20倍左右。

0
相关文章