When an Expression<T>
is compiled, is the resultant code implicitly cached by the framework? I'm thinking along the lines of the static Regex
methods where the framework implicitly compiles and caches the last few regexes.
If compiled Expression<T>
objects are not cached, can you recommend some best practices for keeping the compile-time down or any gotchas that could cause problems if I manually cache an expression?
public MyResultType DoSomething(int arg1, int arg2)
{
var result = invokeHandler(
(IDoSomethingHandler h) => h.DoSomething(arg1, arg2)
);
return result;
}
private TResult invokeHandler<T, TResult>(Expression<Func<T, TResult>> action)
where T : class
{
// Here, I might want to check to see if action is already cached.
var compiledAction = action.Compile();
var methodCallExpr = action as MethodCallExpression;
// Here, I might want to store methodCallExpr in a cache somewhere.
var handler = ServiceLocator.Current.GetInstance<T>();
var result = compiledAction(handler);
return result;
}
In this example, I'm slightly concerned that if I cache the compiled expression, that it will use the values of arg1
and arg2
as they were at the time the expression was compiled, rather than retrieving those values from the appropriate place in the stack (i.e. rather than getting the current values).