C# 反射性能比较

原创 2015年11月19日 18:06:37

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using testInvoke;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Type t = typeof(Person);
            MethodInfo methodInfo = t.GetMethod("Say");
            Person person = new Person();
            string word = "hello";
            Person p = null;
            object[] param = new object[] { word, p, 3 };
            int TestTimes = 10000000; //测试次数,可自行调节看效果

            #region 传统方式反射

            Console.WriteLine("一千万次反射调用性能比较");
            try
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                for (int i = 0; i < TestTimes; i++)
                {
                    methodInfo.Invoke(person, param);
                }
                watch.Stop();
                Console.WriteLine(TestTimes.ToString() + " times 传统Invoke方式反射: " + watch.ElapsedMilliseconds + "ms");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("传统方式反射 直接错误:" + ex.Message);
                Console.WriteLine("传统方式反射 内部错误:" + ex.InnerException.Message);
            }
            #endregion

            #region 实例化反射
            try
            {
                //Stopwatch watch = new Stopwatch();
                //watch.Start();
                //for (int i = 0; i < TestTimes; i++)
                //{
                //    Assembly Asm = Assembly.Load("testInvoke");//反射出空间
                //    Type type = Asm.GetType("testInvoke.Person");//反射出空间下的类
                //    object AssClas = Activator.CreateInstance(type);//动态实例化反射回来的指定空间下的指定类
                //    IPerson objPerson = (Person)AssClas; ////转换为接口类型
                //    objPerson.Say(ref word, out p, 3);
                //}
                //watch.Stop();
                //Console.WriteLine(TestTimes.ToString() + " times invoked by InstanceReflection@1: " + watch.ElapsedMilliseconds + "ms");

                Stopwatch watch = new Stopwatch();
                Assembly Asm = Assembly.Load("ConsoleApplication1");//反射出空间
                Type type = Asm.GetType("ConsoleApplication1.Person");//反射出空间下的类
                object AssClas = Activator.CreateInstance(type);//动态实例化反射回来的指定空间下的指定类
                IPerson objPerson = (Person)AssClas; //转换为接口类型
               
                watch.Start();
                for (int i = 0; i < TestTimes; i++)
                {
                    objPerson.Say(ref word, out p, 3);
                }
                watch.Stop();
                Console.WriteLine(TestTimes.ToString() + " times 实例化Load反射: " + watch.ElapsedMilliseconds + "ms");

            }
            catch (System.Exception ex)
            {
                Console.WriteLine("实例化反射 错误:" + ex.Message);
            }
            #endregion


            #region 快速反射
            try
            {
                Stopwatch watch1 = new Stopwatch();
                FastInvoke.FastInvokeHandler fastInvoker = FastInvoke.GetMethodInvoker(methodInfo);
                watch1.Start();
                for (int i = 0; i < TestTimes; i++)
                {
                    fastInvoker(person, param);
                }
                watch1.Stop();
                Console.WriteLine(TestTimes.ToString() + " times 快速FastInvoke反射: " + watch1.ElapsedMilliseconds + "ms");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("快速反射 错误:" + ex.Message);
            }
            #endregion


            #region 直接调用
            try
            {
                Stopwatch watch2 = new Stopwatch();
                watch2.Start();
                for (int i = 0; i < TestTimes; i++)
                {
                    person.Say(ref word, out p, 3);
                }
                watch2.Stop();
                Console.WriteLine(TestTimes.ToString() + " times 直接new调用: " + watch2.ElapsedMilliseconds + "ms");
                Console.Read();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("直接调用 错误:" + ex.Message);
            }
            #endregion
        }
    }
    public class Person : IPerson
    {
        string s1 = "";
        string s2 = "";
        public void Say(ref string word, out Person prop, int s)
        {
            s1 = word;
            Person prop1 = new Person();
            prop1.s1 = s.ToString();
            prop = prop1;
        }
    }
    public interface IPerson
    {
        void Say(ref string s, out Person p, int i);
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;

namespace testInvoke
{
    class FastInvoke
    {
        public delegate object FastInvokeHandler(object target, object[] paramters);

        static object InvokeMethod(FastInvokeHandler invoke, object target, params object[] paramters)
        {
            return invoke(null, paramters);
        }

        public static FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo)
        {
            DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object[]) }, methodInfo.DeclaringType.Module);
            ILGenerator il = dynamicMethod.GetILGenerator();
            ParameterInfo[] ps = methodInfo.GetParameters();
            Type[] paramTypes = new Type[ps.Length];
            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (ps[i].ParameterType.IsByRef)
                    paramTypes[i] = ps[i].ParameterType.GetElementType();
                else
                    paramTypes[i] = ps[i].ParameterType;
            }
            LocalBuilder[] locals = new LocalBuilder[paramTypes.Length];

            for (int i = 0; i < paramTypes.Length; i++)
            {
                locals[i] = il.DeclareLocal(paramTypes[i], true);
            }
            for (int i = 0; i < paramTypes.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_1);
                EmitFastInt(il, i);
                il.Emit(OpCodes.Ldelem_Ref);
                EmitCastToReference(il, paramTypes[i]);
                il.Emit(OpCodes.Stloc, locals[i]);
            }
            if (!methodInfo.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
            }
            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (ps[i].ParameterType.IsByRef)
                    il.Emit(OpCodes.Ldloca_S, locals[i]);
                else
                    il.Emit(OpCodes.Ldloc, locals[i]);
            }
            if (methodInfo.IsStatic)
                il.EmitCall(OpCodes.Call, methodInfo, null);
            else
                il.EmitCall(OpCodes.Callvirt, methodInfo, null);
            if (methodInfo.ReturnType == typeof(void))
                il.Emit(OpCodes.Ldnull);
            else
                EmitBoxIfNeeded(il, methodInfo.ReturnType);

            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (ps[i].ParameterType.IsByRef)
                {
                    il.Emit(OpCodes.Ldarg_1);
                    EmitFastInt(il, i);
                    il.Emit(OpCodes.Ldloc, locals[i]);
                    if (locals[i].LocalType.IsValueType)
                        il.Emit(OpCodes.Box, locals[i].LocalType);
                    il.Emit(OpCodes.Stelem_Ref);
                }
            }

            il.Emit(OpCodes.Ret);
            FastInvokeHandler invoder = (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler));
            return invoder;
        }

        private static void EmitCastToReference(ILGenerator il, System.Type type)
        {
            if (type.IsValueType)
            {
                il.Emit(OpCodes.Unbox_Any, type);
            }
            else
            {
                il.Emit(OpCodes.Castclass, type);
            }
        }

        private static void EmitBoxIfNeeded(ILGenerator il, System.Type type)
        {
            if (type.IsValueType)
            {
                il.Emit(OpCodes.Box, type);
            }
        }

        private static void EmitFastInt(ILGenerator il, int value)
        {
            switch (value)
            {
                case -1:
                    il.Emit(OpCodes.Ldc_I4_M1);
                    return;
                case 0:
                    il.Emit(OpCodes.Ldc_I4_0);
                    return;
                case 1:
                    il.Emit(OpCodes.Ldc_I4_1);
                    return;
                case 2:
                    il.Emit(OpCodes.Ldc_I4_2);
                    return;
                case 3:
                    il.Emit(OpCodes.Ldc_I4_3);
                    return;
                case 4:
                    il.Emit(OpCodes.Ldc_I4_4);
                    return;
                case 5:
                    il.Emit(OpCodes.Ldc_I4_5);
                    return;
                case 6:
                    il.Emit(OpCodes.Ldc_I4_6);
                    return;
                case 7:
                    il.Emit(OpCodes.Ldc_I4_7);
                    return;
                case 8:
                    il.Emit(OpCodes.Ldc_I4_8);
                    return;
            }

            if (value > -129 && value < 128)
            {
                il.Emit(OpCodes.Ldc_I4_S, (SByte)value);
            }
            else
            {
                il.Emit(OpCodes.Ldc_I4, value);
            }
        }
    }
}




【C#】:浅谈反射机制

什么是反射?         反射提供了封装程序集、模块和类型的对象(Type 类型)。可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。如果代...

【C#语法】详解C#中的反射(Assembly)机制

一 引言         反射机制是C#中比较有特色的一种技术。它使我们编程时可以更加灵活,能够通过类或者方法名称能够很方便的构造类和调用方法,虽然有一些微不足道的性能损失。 我们先来看一下反射的定义...

缓存对象类型信息与使用GetType、typeof()的性能比较

开始很热衷于使用反射,现在了解到反射带来的性能损失便开始着手怎么避免使用反射了。因为一直对GetType方法的效率很怀疑,心里没底,到底要不要加一个字段保存对象的类型信息,所以做了一个测试。using...

C# typeof() 和 GetType()区别

总得来说他们都是为了获取某个实例具体引用的数据类型System.Type。 1、GetType()方法继承自Object,所以C#中任何对象都具有GetType()方法,x.GetType(),其中...
  • letianok
  • letianok
  • 2012年02月14日 10:50
  • 12748

C# 反射性能

C# 创建对象可以直接用new,也可以用反射,下面测试一下反射创建的性能如何, 这里可以比较一下,构造方法带参数和不带参数的区别。 先创建一个测试类,分为构造函数带参数和不带参数,两种情况来测试 ...

C#中使用反射的优缺点

优点:             反射提高了程序的灵活性和扩展性,降低耦合性,提高自适应能力。它允许程序创建和控制任何类的对象,无需提前硬编码目标类;   缺点:            1、性能问题:使...

C#中各种数组的性能比较

  • 2010年03月07日 09:08
  • 4KB
  • 下载

C#和Java矩阵相乘运算性能比较

  • 2010年05月27日 13:46
  • 209KB
  • 下载

C#为什么使用AS和IS运算符及其性能比较

AS和IS对于如何安全的“向下转型”提供了较好的解决方案,因此我们有两种转型的选择: 1、使用AS运算符进行类型转换 2、先使用IS运算符判断类型是否可以转换,再使用()运算符进行显示的转换 ...

C#性能比较

  • 2015年02月17日 13:42
  • 111KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:C# 反射性能比较
举报原因:
原因补充:

(最多只允许输入30个字)