浅谈DiscuzNT的数据层提供程序

来源:互联网 发布:抓取微信文章图片 php 编辑:程序博客网 时间:2024/06/16 11:47

相信大家看了Discuz源码的 不免对一些地方有些看法

这里是自己前段时间学习,以及通过达达的指教总结得出来的一点点经验,大家可以参考下

Discuz为了支持多种数据库,所以采取了反射的方法,但是大家知道反射的性能损失非常大的

private static void GetProvider()
   {
    try
    {
     _instance = (IDataProvider)Activator.CreateInstance(Type.GetType(string.Format("Discuz.Data.{0}.DataProvider, Discuz.Data.{0}", BaseConfigs.GetDbType), false, true));
    }
    catch
    {
     throw new Exception("请检查DNT.config中Dbtype节点数据库类型是否正确,例如:SqlServer、Access、MySql");
    }
   }

前段时间bbsmax http://www.bbsmax.com (非常不错的一个.net论坛程序)的达达提供了另外一种方法

private static CreateInstance<T> CreateInstanceHandler()
        {
            Type baseType = typeof(T);
            Type newType = CreateType();

            if (newType != null)
            {
                DynamicMethod method = new DynamicMethod(string.Empty, baseType, null, baseType.Module);

                ILGenerator iLGenerator = method.GetILGenerator();

                iLGenerator.DeclareLocal(baseType, true);
                iLGenerator.Emit(OpCodes.Newobj, newType.GetConstructor(new Type[0]));
                iLGenerator.Emit(OpCodes.Stloc_0);
                iLGenerator.Emit(OpCodes.Ldloc_0);
                iLGenerator.Emit(OpCodes.Ret);

                return (CreateInstance<T>)method.CreateDelegate(typeof(CreateInstance<T>));
            }

            return null;
        }

internal delegate T CreateInstance<T>(); 这是委托的声明

即采用 DynamicMethod的方法 这种方法确实性能会有很大的提高

前段时间在国外的一个博客上也看到了关于直接引用 反射 DynamicMethod的性能比较,把它的实例下载下来了 测试结果如下

------ Object Creation ------
direct - object creation: 39ms
dynamic method - object creation: 51ms
reflection - object creation: 306ms
------ Property Get ------
direct - property get: 20ms
dynamic method - property get: 45ms
reflection - property get: 1800ms
------ Property Set ------
direct - property set: 26ms
dynamic method - property set: 52ms
reflection - property set: 2366ms
------ Instance Method Call ------
direct - instance method call: 50ms
dynamic method - instance method call: 123ms
reflection - instance method call: 3069ms
------ Static Method Call ------
direct - static method call: 24ms
dynamic method - static method call: 121ms
reflection - static method call: 2931ms

 

上面的结果中每一项中的 direct是指直接引用

dynamic method则是采用动态方法

reflection 即是采用反射的方法即discuz的Activator.CreateInstance

通过上面的数据大家可以清晰的看到,虽然动态方法的性能比直接引用 direct invoke要慢但是比反射方法 性能却提高了几十倍

不过由于只是在第一次编译的时候会影响速度 所以其实影响也不是很大

原创粉丝点击