Question

I am using reflection to call methods, and invoking the methods using Invoke() doesn't do it for me, too slow. I generate thousands - millions of method calls, it is a test automation tool. At compile time I have no clue about the method name, parameter type(s) or return type. So Jon Skeet's article on using delegates to cache reflection is no help here. Here is what I have:

foreach (MethodInfo method in _methods)
{
    foreach (var p in method.GetParameters())
    {
        var paramValue = Utils.RandomizeParamValue(p.ParameterType.Name);
        parameters.Add(paramValue);
    }
    var result = method.Invoke(_objectInstance, parameters.ToArray());
    //_objectInstance is the class instance of which the method is a member of.
}

I have researched the DLR (ExpandoObject, DynamicObject) but I am not sure it has what I am looking for. What I am looking for is a way to bypass the overhead of reflection, or cache method invocations, even if it turns out be an ugly hack. Is there a common hack that I have missed? Could I go down to IL level and do some tricks there?

Was it helpful?

Solution

One option is to use expression tree to build delegate that will call your methods. MSDN have introduction in Expression Trees article and in particular you'll need MethodCallExpression

Create an expression sample (from MethodCallExpression article):

string[,] gradeArray =  
    { {"chemistry", "history", "mathematics"}, {"78", "61", "82"} };
var  arrayExpression = Expression.Constant(gradeArray);

// Create a MethodCallExpression that represents indexing 
// into the two-dimensional array 'gradeArray' at (0, 2). 
// Executing the expression would return "mathematics".
var  methodCallExpression = Expression.ArrayIndex(
    arrayExpression,
    Expression.Constant(0),
    Expression.Constant(2));

Compile an expression to delegate sample (from main article):

Expression<Func<int, bool>> expr = num => num < 5;
Func<int, bool> result = expr.Compile();
Console.WriteLine(result(4));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top