Compiled Expression Trees misunderstanding?

.net-4.0 c# expression-trees

Question

I have this expression :

Expression<Func<string, bool>> f = s => s.Length < 5;

enter image description here

ParameterExpression p = Expression.Parameter (typeof (string), "s");
MemberExpression stringLength = Expression.Property (p, "Length");
ConstantExpression five = Expression.Constant (5);
BinaryExpression comparison = Expression.LessThan (stringLength, five);
Expression<Func<string, bool>> lambda= Expression.Lambda<Func<string, bool>> (comparison, p);

//lets : test

Func<string, bool> runnable = lambda.Compile();
Console.WriteLine (runnable ("kangaroo")); // False
Console.WriteLine (runnable ("dog")); //True

I want to ask about the .Compile()

What does it compile ? And what is the difference between the first execution vs later executions...?

Compile should be something that happens once and not happens again later ....

What / How does it help me ?

Accepted Answer

When you are building the expression tree at runtime there's no code emitted. It's a way to represent .NET code at runtime.

Once you call the .Compile method on the expression tree the actual IL code is emitted to convert this expression tree into a delegate (Func<string, bool> in your case) that you could invoke at runtime. So the code that this expression tree represents can be executed only after you compile it.

Calling Compile is an expensive operation. Basically you should be calling it once and then caching the resulting delegate that you could use to invoke the code many times.


Popular Answer

Compile() takes the expression tree (which is a data representation of some logic) and converts it to IL which can then be executed directly as a delegate.

The only difference between the first execution and later executions is the possibility that Compile() won't trigger the JIT compilation from IL to native processor code. That may happen on first execution.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why