最近在研究一個(gè)可配置系統(tǒng)的框架,在代碼中大量使用了反射的方法,雖然借鑒到其他的語言,如Java中反射性能都比較差,但是想到C#既然是一種強(qiáng)類型的語言,對(duì)于AppDomain中的類的調(diào)用應(yīng)該性能不會(huì)差很多。
今天在mvp站點(diǎn)上看到有人說反射的性能很差,要避免使用,就寫了一個(gè)簡(jiǎn)單的例子測(cè)試了一下
測(cè)試類如下:
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; }
}
}
首先我們對(duì)于對(duì)象的構(gòu)造進(jìn)行測(cè)試
測(cè)試代碼如下
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();
}
測(cè)試結(jié)果直接調(diào)用的時(shí)間為16ms左右,而反射調(diào)用的則始終維持在5s 520ms左右,直接效率比較接近350倍。
對(duì)于這個(gè)測(cè)試,很有趣的一點(diǎn)是:
如果將test2中的Type theTest = Type.GetType("ReflectionTest.Test.CTester");
移到循環(huán)之外,則相應(yīng)的運(yùn)行時(shí)間下降為1s 332 ms , 效率相差為20倍左右。
今天在mvp站點(diǎn)上看到有人說反射的性能很差,要避免使用,就寫了一個(gè)簡(jiǎn)單的例子測(cè)試了一下
測(cè)試類如下:
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; }
}
}
首先我們對(duì)于對(duì)象的構(gòu)造進(jìn)行測(cè)試
測(cè)試代碼如下
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();
}
測(cè)試結(jié)果直接調(diào)用的時(shí)間為16ms左右,而反射調(diào)用的則始終維持在5s 520ms左右,直接效率比較接近350倍。
對(duì)于這個(gè)測(cè)試,很有趣的一點(diǎn)是:
如果將test2中的Type theTest = Type.GetType("ReflectionTest.Test.CTester");
移到循環(huán)之外,則相應(yīng)的運(yùn)行時(shí)間下降為1s 332 ms , 效率相差為20倍左右。

