Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it expensive to parse an ExpressionTree?

I am currently reading through the MSDN, Walkthrough: Creating an IQueryable LInQ Provider and there is a lot of use of the ExpressionVisitor.

It makes me wonder, is it an expensive operation to use this?

Is it as expensive as Reflection?

like image 475
Phillip Scott Givens Avatar asked Nov 13 '22 12:11

Phillip Scott Givens


1 Answers

No, it should be quite cheap to traverse an expression tree with an ExpressionVisitor.

There is no run-time cost at all needed to parse the expression tree. The compiler does all the work of turning an Expression into an object tree at compile time. There isn't even much run-time reflection going on when the objects in question are created in memory. When you see a method call like:

SomeMethod(Foo x => x.Property);

and SomeMethod's argument is Expression typed, then the compiler converts the code into IL which acts like you had written something like this:

SomeMethod(new MemberExpression {
  Expression = new ParameterExpression("x", typeof(Foo)),
  Member = typeof(Foo).GetProperty("Property")
});

You can look at the generated IL for the full details, or see the worked example in Microsoft's documentation. There is some reflection involved (for example MemberExpressions hold a PropertyInfo reference), but it is all quite fast.

If you have an app you are worried about, you should profile it (e.g. recent versions of Visual Studio have a built in performance profiler) and see which specific parts are slow.

like image 120
Rich Avatar answered Nov 15 '22 06:11

Rich