首页 新闻 会员 周边

Expression的处理

1
悬赏园豆:200 [已解决问题] 解决于 2014-10-06 08:21

听说表达式的性能比反射要高,但我的表达式反而更低,为什么?

            var instanceExp = Expression.Parameter(typeof(object), "instance");

            var method = typeof(string).GetMethod("GetType", new Type[0]);
            var getTypeExp = Expression.Call(instanceExp, method);

            var tmp = Expression.Lambda(getTypeExp, instanceExp).Compile();

            Stopwatch methodWatch = new Stopwatch();
            methodWatch.Start();
            for(int i = 0; i < 1000; i++)
            {
                method.Invoke(1, new object[0]);
            }
            methodWatch.Stop();
            Stopwatch expWatch = new Stopwatch();
            expWatch.Start();
            for (int i = 0; i < 1000; i++)
            {
                tmp.DynamicInvoke(1);
            }
            expWatch.Stop();
            var t1 = methodWatch.ElapsedTicks;
            var t2 = expWatch.ElapsedTicks;
triout的主页 triout | 初学一级 | 园豆:13
提问于:2014-10-06 08:15
< >
分享
最佳答案
0

我也遇到这样的问题。

var tmp = Expression.Lambda(getTypeExp, instanceExp).Compile();

修改为:

var tmp = Expression.Lambda<Func<object, Type>>(getTypeExp, instanceExp).Compile();

再把:

tmp.DynamicInvoke(1);

修改为:

tmp(1);

收获园豆:200
519740105 | 大侠五级 |园豆:5810 | 2014-10-06 08:17

谢谢,确实是。但是为什么呢?好奇怪。

triout | 园豆:13 (初学一级) | 2014-10-06 08:21
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册