Welcome

首页 / 软件开发 / C# / C#中使用反射的使用实现和性能分析

C#中使用反射的使用实现和性能分析2011-04-04最近在研究一个可配置系统的框架,在代码中大量使用了反射的方法,虽然借鉴到其他的语言,如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();
}