设计之美——极限反射加速(代码)

  才起床的时候,总是感觉还是比较不错的感觉,虽然不怎么情愿起来,先来BS下移动,一个破电话给我吵醒,为何呢?說啥要开奥运手机报,還不是赚钱啊,有种免费开,nnd……

  废话不说了,这是骗还在床上写的,大家也就凑合着看,依然是上次的测试代码,贴一下。。

  我忽然觉得新贴下测试结果也许大家会更感兴趣

test1 time past 00:00:00.9062500
克隆加动态委托 time past 00:00:00.7031250
test1 time past 00:00:01.4687500
克隆加动态委托 time past 00:00:00.7031250
test1 time past 00:00:00.8750000
克隆加动态委托 time past 00:00:00.6875000

这是连续的3次测试,嗯 ?发现一个问题,居然比直接执行要快!我也很怀疑,但是不知道为什么,如果你找出原因請告诉我,我觉得也许是克隆比new块一些吧 ,猜的,好了 看起来也许你开始迫不及待了,来看测试代码。

 

            testclass clas  =   new  testclass();
            clas.test1();
            clas.testdle();
            clas.test1();
            clas.testdle();
            clas.test1();
            clas.testdle();

这里是刚才的测试 main主题 大家看好了,我没作弊!

 

    public   class  CTester :  DesignPaterns.Reflection.Class
    
{
        
public CTester()
        
{
            a 
= 10;
        }


        
public void test1()
        
{
            a 
= (a - 0.0001* 1.0001;
        }

        
private double a;
        
public double geta() return a; }

        
public object Clone()
        
{
            
return this.MemberwiseClone();
        }

    }


    
public   class  CTestern : DesignPaterns.Reflection.Class
    
{
        
public CTestern()
        
{
            a 
= 10;
        }


        
public void test1()
        
{
            a 
= (a - 0.0001* 1.0001;
        }

        
private double a;
        
public double geta() return a; }

        
public object Clone()
        
{
            
return this.MemberwiseClone();
        }

    }

一开始以为自定义类的构造时间长,所以特地分开了。结果还是一样的

 


    
public   class  testclass
    
{

       

       
public void testdle()
        
{
            

            DateTime now 
= DateTime.Now;
            
            
for (int i = 0; i < 10000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    CTester aTest 
= DesignPaterns.Reflection.DelegateReflection.Instance.GetObject<CTester>();

                    (aTest 
as DesignPaterns.Reflection.IReflection).InvokeMember("test1");
                }

            }


            TimeSpan spand 
= DateTime.Now - now;
            Console.WriteLine(
"克隆加动态委托 time past " + spand.ToString());
        }


        
public void test1()
        
{

            DateTime now 
= DateTime.Now;

            
for (int i = 0; i < 10000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    CTestern aTest 
= new CTestern();
                    
                    aTest.test1();
                }

            }


            TimeSpan spand 
= DateTime.Now - now;
            Console.WriteLine(
"test1 time past " + spand.ToString());
        }

}

是的没错,完全反射执行。。

要看大类么?想看么? 嘿嘿 会给你看的

 

     /// <summary>
    
/// #region license
    
/// // **************************************************
    
/// // Copyright (c) 2008 fengjian (icesun963@Gmail.com)
    
/// // All rights reserved.
    
/// // **************************************************
    
/// #endregion
    
/// 对象缓存
    
/// </summary>

     public   class  ReflectionCache : Classes.DisposableClass
    
{

         
protected ReflectionCache()
         
{
         }



        
/// <summary>
        
/// 反射对象母模版
        
/// </summary>

        List<ICloneable> _ReflectionObjMaster = new List<ICloneable>();

        
/// <summary>
        
/// 反射对象字典 用于检索对象
        
/// </summary>

        Dictionary<Type, ReflectionObjectInfo> _ReflectionDic = new Dictionary<Type, ReflectionObjectInfo>();

        Dictionary
<string, Type> _TypeDic = new Dictionary<string, Type>();


        
/// <summary>
        
/// 获取对象
        
/// </summary>
        
/// <typeparam name="T"></typeparam>
        
/// <param name="type"></param>
        
/// <param name="args"></param>
        
/// <returns></returns>

        public object GetObject(string type, params object[] args)
        
{
            
if (_TypeDic.ContainsKey(type))
            
{
                
return GetObject<ICloneable>(_TypeDic[type], args);
            }

            
else
            
{
                
return null;
            }

        }


        
/// <summary>
        
/// 注册一个类
        
/// </summary>
        
/// <param name="type"></param>

        public void RegType(Type type)
        
{
            
if (!_TypeDic.ContainsKey(type.FullName))
            
{
                _TypeDic.Add(type.FullName, type);
            }

        }


        
/// <summary>
        
/// 注册一个别名
        
/// </summary>
        
/// <param name="type"></param>

        public void RegType(Type type, string newname)
        
{
            
if (!_TypeDic.ContainsKey(newname))
            
{
                _TypeDic.Add(newname, type);
            }

        }


        
public T GetObject<T>params object[] args)
        
{
            Type type 
= typeof(T);
            
int index = FindObject(type, args);
            
if (index >= 0)
            
{
                
return (T)_ReflectionObjMaster[index];
            }

            
else
            
{
                ICloneable newobj 
= Activator.CreateInstance(type, args) as ICloneable;
                
if (newobj == null)
                
{
                    
throw new Exception("不提供不支持克隆接口的对象!");
                }

                
return (T)_ReflectionObjMaster[AddtoCache(newobj, args)];
            }

        }



        
/// <summary>
        
/// 查找对象
        
/// </summary>
        
/// <param name="t"></param>
        
/// <param name="args"></param>
        
/// <returns></returns>

        protected int FindObject(Type t, params object[] args)
        
{
            
if (_ReflectionDic.ContainsKey(t))
            
{

                    
foreach (KeyValuePair<intobject[]> var in _ReflectionDic[t].ArgsDic)
                    
{
                        
if (var.Value.Length == args.Length)
                        
{
                            
int cout = 0;
                            
for (int i = 0; i < var.Value.Length; i++)
                            
{
                                
if (var.Value[i].GetType() == args[i].GetType())
                                
{
                                    cout
++;
                                }

                            }

                            
if (cout == var.Value.Length )
                            
{
                                
return var.Key;
                            }

                        }

                    }

                
            }

            
return -1;
        }


        
protected override void Dispose(bool disposing)
        
{
            
//由于Dispose方法可能被多线程调用,
            
//所以加锁以确保线程安全
            lock (this)
            
{
                
if (disposing)
                
{

                    
try
                    
{
                        _ReflectionDic.Clear();
                        _ReflectionObjMaster.Clear();
                        
//说明对象的Finalize方法并没有被执行,
                        
//在这里可以安全的引用其他实现了Finalize方法的对象
                    }

                    
finally
                    
{
                        
base.Dispose(disposing);
                    }

                }

            }

           
        }


        
/// <summary>
        
/// 添加到缓存
        
/// </summary>
        
/// <param name="obj">The obj.</param>
        
/// <param name="args">The args.</param>
        
/// <returns></returns>

        protected virtual int AddtoCache(ICloneable obj, object[] args)
        
{
            
lock (_ReflectionObjMaster)
            
{
               
                
lock (_ReflectionDic)
                
{
                    _ReflectionObjMaster.Add(obj);
                    
if (_ReflectionDic.ContainsKey(obj.GetType()))
                    
{
                        _ReflectionDic[obj.GetType()].ArgsDic.Add(_ReflectionObjMaster.Count 
-1, args);
                     
                    }

                    
else
                    
{
                        _ReflectionDic.Add(obj.GetType(), 
new ReflectionObjectInfo(obj.GetType(), _ReflectionObjMaster.Count -1, args));
                    }


                    
return _ReflectionObjMaster.Count -1;
                }

            }


        }



    }

就是一个对对象缓存然后克隆的,demodemo 大家参考下就好了。

 

     /// <summary>
    
/// #region license
    
/// // **************************************************
    
/// // Copyright (c) 2008 fengjian (icesun963@Gmail.com)
    
/// // All rights reserved.
    
/// // **************************************************
    
/// #endregion
    
///  反射对象定义
    
/// </summary>

     class  ReflectionObjectInfo : Classes.DisposableClass
    
{

        
public ReflectionObjectInfo(Type type, int index, params object[] args)
        
{
            _Type 
= type;
            ArgsDic.Add(index, args);
        }


        Type _Type;
        
/// <summary>
        
/// 类型
        
/// </summary>

        public Type Type
        
{
            
get return _Type; }
        }


        
/// <summary>
        
/// 参数和对象索引
        
/// </summary>

        Dictionary<intobject[]> _ArgsDic = new Dictionary<intobject[]>();

        
/// <summary>
        
/// 参数和对象索引
        
/// </summary>

        public Dictionary<intobject[]> ArgsDic
        
{
            
get return _ArgsDic; }
        }


    }
     /// <summary>
    
/// 委托接口
    
/// </summary>

     public   interface  IReflection
    
{
        
/// <summary>
        
/// 执行一个方法
        
/// </summary>
        
/// <param name="name"></param>
        
/// <param name="target"></param>
        
/// <param name="args"></param>
        
/// <returns></returns>

        object InvokeMember(string name, params object[] args);
        List
<IDelegateDefine> DelegateDefine get;set;}

    }



    
/// <summary>
    
/// #region license
    
/// // **************************************************
    
/// // Copyright (c) 2008 fengjian (icesun963@Gmail.com)
    
/// // All rights reserved.
    
/// // **************************************************
    
/// #endregion
    
/// 
    
/// </summary>

     public   class  Class : DisposableClass, IReflection
    
{

        List
<IDelegateDefine> _DelegateDefine = new List<IDelegateDefine>();

        List
<IDelegateDefine> IReflection.DelegateDefine
        
{
            
get return _DelegateDefine; }
            
set { _DelegateDefine = value; }
        }


        
IReflection 成员
    }

有点乱,而且肚子饿了,直接贴代码了,有空再补说明了。。。

 

     /// <summary>
    
/// 基本对象定义
    
/// </summary>

     public   abstract   class  DelegateDefine : IDelegateDefine
    
{

        
string _DelegateName;

        
/// <summary>
        
/// 名称
        
/// </summary>
        
/// <value></value>

        public string DelegateName
        
{
            
get return _DelegateName; }
            
protected set { _DelegateName = value; }
        }


        
object[] _Args;

        Delegate _Delegate;


        
IDelegateDefine 成员
    }
     /// <summary>
    
/// 委托对象定义
    
/// </summary>

     public   interface  IDelegateDefine
    
{
        
/// <summary>
        
/// 名称
        
/// </summary>

        string DelegateName get;}
        
/// <summary>
        
/// 参数
        
/// </summary>

        object[] Args get;set;}
        
/// <summary>
        
/// 委托
        
/// </summary>

        Delegate Delegate get;}
        
/// <summary>
        
/// 调用
        
/// </summary>
        
/// <returns></returns>

        object Invoke();
    }

}
     public   class  ObjectDelegateDefine : DelegateDefine
    
{

        
/// <summary>
        
/// 建立的速度不快 很慢!!
        
/// </summary>
        
/// <param name="t"></param>
        
/// <param name="obj"></param>
        
/// <param name="methodname"></param>

        protected ObjectDelegateDefine(Type delegatetype, object obj, string methodname)
        
{
            
this.Delegate = Delegate.CreateDelegate(delegatetype, obj, methodname);
            
this.DelegateName = methodname;
        }


        
public ObjectDelegateDefine(object obj, string methodname)
            : 
this(typeof(voidDelegate), obj, methodname)
        
{

        }


        
delegate void voidDelegate();

        
public override object Invoke()
        
{
            (
this.Delegate as voidDelegate)();
            
return null;
        }


        
/// <summary>
        
/// 用于注册
        
/// </summary>

        public static void Method()
        
{
        }


    }

    
/// <summary>
    
/// #region license
    
/// // **************************************************
    
/// // Copyright (c) 2008 fengjian (icesun963@Gmail.com)
    
/// // All rights reserved.
    
/// // **************************************************
    
/// #endregion
    
/// 反射执行助手类
    
/// </summary>

     class  InvokeMemberHelper
    
{

        
反射对象帮助

        
/// <summary>
        
/// 反射注册类型列表
        
/// </summary>

        List<Type> _DelegateTypeList = new List<Type>();

        Dictionary
<Type, Dictionary<ParameterInfo[], int>> _TypeDic = new Dictionary<Type, Dictionary<ParameterInfo[], int>>();

        
delegate void voiddelgate();

       
static InvokeMemberHelper _Instance;
        
public static InvokeMemberHelper Instance
        
{
            
get
            
{
                
if (_Instance == null)
                
{
                    _Instance 
= new InvokeMemberHelper();
                }

                
return InvokeMemberHelper._Instance;
            }

            
set { _Instance = value; }
        }


        
private InvokeMemberHelper()
        
{
            RegDelegateType(
typeof(ObjectDelegateDefine), typeof(ObjectDelegateDefine).GetMethod("Method"));
        }


        
public void build(IReflection myclass)
        
{
            
//反射委托建立
            foreach (MethodInfo var in myclass.GetType().GetMethods())
            
{
                Type t 
= GetDelegate(var);
                
if (t != null)
                
{
                    
//建立委托
                    
//这里该使用一个工厂生产对象 为了演示就不管了
                    myclass.DelegateDefine.Add(new ObjectDelegateDefine(myclass, var.Name));
                }

            }

        }




        
/// <summary>
        
/// 获取委托类型
        
/// </summary>
        
/// <param name="minfo"></param>
        
/// <returns></returns>

        public Type GetDelegate(MethodInfo minfo)
        
{
            
int index = FindDelegate(minfo);
            
if (index != -1)
            
{
                
return _DelegateTypeList[index];
            }

            
return null;
        }


        
/// <summary>
        
/// 注册一个反射类型
        
/// </summary>
        
/// <param name="dtype"></param>

        public void RegDelegateType(Type dtype, MethodInfo minfo)
        
{
            
lock (_DelegateTypeList)
            
{
                
lock (_TypeDic)
                
{
                    Type returntype 
= minfo.ReturnType;
                    ParameterInfo[] argstype 
= minfo.GetParameters();

                    
if (_TypeDic.ContainsKey(returntype))
                    
{

                        Dictionary
<ParameterInfo[], int> subdic = _TypeDic[returntype];
                        
if (!subdic.ContainsKey(argstype))
                        
{
                            _DelegateTypeList.Add(dtype);
                            subdic.Add(argstype, _DelegateTypeList.Count);
                        }

                    }

                    
else
                    
{
                        Dictionary
<ParameterInfo[], int> subdic = new Dictionary<ParameterInfo[], int>();
                        _DelegateTypeList.Add(dtype);
                        subdic.Add(argstype, _DelegateTypeList.Count 
-1);
                        _TypeDic.Add(returntype, subdic);
                    }

                }

            }

        }


        
/// <summary>
        
/// 通过成员定义查找匹配的对象
        
/// </summary>
        
/// <param name="minfo"></param>
        
/// <returns></returns>

        protected int FindDelegate(MethodInfo minfo)
        
{
            Type returntype 
= minfo.ReturnType;
           
            
if (_TypeDic.ContainsKey(returntype))
            
{
                 ParameterInfo[] argstype 
= minfo.GetParameters();
                Dictionary
<ParameterInfo[], int> subdic = _TypeDic[returntype];
                
if (subdic.ContainsKey(argstype))
                
{
                    
return subdic[argstype];
                }

                
foreach (KeyValuePair<ParameterInfo[], int> var in subdic)
                
{
                    
int count = 0;
                    
if (var.Key.Length == argstype.Length)
                    
{
                        
for (int i = 0; i < var.Key.Length ; i++)
                        
{
                            
if (var.Key[i] == argstype[i]) count++;
                        }

                    }

                    
if (count == var.Key.Length)
                    
{
                        
return var.Value;
                    }

                }

            }


            
return -1;
        }


    }
    /// <summary>
    
/// #region license
    
/// // **************************************************
    
/// // Copyright (c) 2008 fengjian (icesun963@Gmail.com)
    
/// // All rights reserved.
    
/// // **************************************************
    
/// #endregion
    
/// 委托反射
    
/// </summary>

     public   class  DelegateReflection : ReflectionCache
    
{
        
static DelegateReflection _Instance;
        
public static DelegateReflection Instance
        
{
            
get
            
{
                
if (_Instance == null)
                
{
                    _Instance 
= new DelegateReflection();
                }

                
return DelegateReflection._Instance;
            }

            
set { _Instance = value; }
        }


        
private DelegateReflection()
        
{
        }


        
protected override int AddtoCache(ICloneable obj, object[] args)
        
{
            
if (obj is IReflection)
            
{
                InvokeMemberHelper.Instance.build(obj 
as IReflection);
            }

            
return base.AddtoCache(obj, args);
        }

    }

贴完了,有点多。。。。

也很乱,我知道,嗯,这里只对 void (void) 这样的函数进行了处理,本来还有个工厂的,不过暂时懒得写了,代码有点乱,大家也多担待,有什么问题,可以直接留言,如果少了那部分,如果我有贴漏的话无会补上,如果需要完整代码請留言,有空我会打包上来的。

希望大家喜欢她 :)

PS:那个速度有点问题 由于个人的粗心忘记修改了一个过程也就是直接运算的类的继承,直接的运算速度是

00:00:00.04750000左右。我这里加上了初始化也就慢了20倍但是相对以前的数百倍来说 ,确实是个好消息,不是么,如果除去初始化,我相信效果会让人满意的 !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值