衆所周知,C#的反射性能開銷比較大,比如通過反射的方式來調用一個函數, 相比直接調用,反射下的性能是急劇下降的。
爲了加強性能,可以通過MethodInfo來創建Delegate,通過調用Delegate來加強性能。
我們通過以下測試代碼來測試一下,下面3種函數調用的性能消耗:
1.直接函數調用
2.通過delegate調用
3.通過反射調用
4.通過動態修改IL代碼來加速調用(待嘗試)
using System;
using System.Reflection;
using System.Diagnostics;
namespace ConsoleApp2
{
public delegate void VoidFuncVoid();
class Test
{
public void on_xxx()
{
float x = 100.0f;
x *= x * x * x * x * x * x * x;
}
}
class Program
{
static void Main(string[] args)
{
Test test = new Test();
var me = test.GetType().GetMethod("on_xxx");
var de = (VoidFuncVoid)me.CreateDelegate(typeof(VoidFuncVoid), test);
Stopwatch sw = new Stopwatch();
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
test.on_xxx();
}
sw.Stop();
Console.WriteLine("call method with direct " + sw.ElapsedTicks);
sw.Reset();
}
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
de();
}
sw.Stop();
Console.WriteLine("call method with delegate " + sw.ElapsedTicks);
sw.Reset();
}
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
me.Invoke(test, null);
}
sw.Stop();
Console.WriteLine("call method with reflection " + sw.ElapsedTicks);
sw.Reset();
}
Console.ReadKey();
}
}
}
輸出結果如下:
總結:通過delegate調用性能的性能開銷最小,甚至比代碼直接調用函數更小。