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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With