用delegate调用替代基于反射的函数调用

梦想游戏人
目录:
C#

众所周知,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调用性能的性能开销最小,甚至比代码直接调用函数更小。

Scroll Up