Expression Tree and Compile method

c# expression-trees lambda

Question

The focus of this is theCompile manner ofExpression Type. I apologize for being naive since I am a latecomer. I've been reading about creating expressions that allow executable code to be changed dynamically. And as long as for the variable inputs/environment (say for various values for any given constant, parameter, or member expression), it makes sense to me when it comes to outputting lambda expression from a given expression tree. If there is no change in the environment, I assume it would be perfect if I could cache (re-use) lambdas that are produced or built from an expression tree.

Question: Does CLR always produce lambda expressions, even if the environment hasn't changed? If so, what is the best way to prevent compilation of lambda expression if the environment remains unchanged?

1
1
6/17/2013 3:23:00 PM

Accepted Answer

A piece of code may simply be represented by a lambda expression by calling this, calling that, comparing these arguments, returning something, etc. Similar to how JIT works from IL or how you would accomplish it in a code editor.

Compile emits an object from a certain lambda expression. The delegate does not alter after lambda has been compiled into it (the lambda remains unchanged too, because it is immutable).

This does not imply that delegates cannot receive arguments or invoke methods on objects of any type. This only indicates that the delegate's IL is unchanged. Additionally, generated delegate instances may be cached.

2
6/17/2013 3:34:32 PM

Popular Answer

Lambda expressions are not cached by CLR.Compile() returns a fresh delegate each time.

However, caching should be simple using a method similar to this:

public Func<T> Get<T>(Expression<Func<T>> expression)
{
    string key = expression.Body.ToString();

    Func<T> result;
    if (!_cache.TryGetValue(key, out result)) {
        result = expression.Compile();
        _cache.Add(key, result);
    }

    return result;
}


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow