听说表达式的性能比反射要高,但我的表达式反而更低,为什么?
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;
我也遇到这样的问题。
把
var tmp = Expression.Lambda(getTypeExp, instanceExp).Compile();
修改为:
var tmp = Expression.Lambda<Func<object, Type>>(getTypeExp, instanceExp).Compile();
再把:
tmp.DynamicInvoke(1);
修改为:
tmp(1);
谢谢,确实是。但是为什么呢?好奇怪。