A Fast Alternative to MethodInfo.Invoke

Not surprisingly, calls to MethodInfo.Invoke are slow for the same reasons outlined that were outlined in A Fast Alternative to Activator.CreateObject.

The same approach can be used to generate methods that will invoke the MethodInfo instance, but provide an amazing performance boost by handling validation up front once rather than upon every invocation.

            public static Func<TTarget, TResult> GenerateFastInvoker<TTarget, TResult>(MethodInfo method)
            {
                #if DEBUG
                    ParameterExpression targetExpression = Expression.Parameter(typeof(TTarget), "target");
                #else
                    ParameterExpression targetExpression = Expression.Parameter(typeof(TTarget));
                #endif

                Expression<Func<TTarget, TResult>> expression = Expression.Lambda<Func<TTarget, TResult>>(
                    Expression.Call(
                        targetExpression,
                        method),
                    targetExpression);
                Func<TTarget, TResult> functor = expression.Compile();
                return functor;
            }
          

The same caveats apply as before, but the performance increase is well worth it. Further, the same alterations used to create weakly-typed fast activators can be applied to generate weakly-typed fast invokers.



Tags

  • .NET

Revisions

  • 9/22/2012 - Article published.