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?
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?
不,用 . 遍历表达式树应该很便宜ExpressionVisitor
。
解析表达式树根本不需要运行时成本。编译器在编译时完成将表达式转换为对象树的所有工作。当有问题的对象在内存中创建时,甚至没有太多的运行时反射。当您看到如下方法调用时:
SomeMethod(Foo x => x.Property);
并且 SomeMethod 的参数被Expression
输入,然后编译器将代码转换为 IL,就像你写了这样的东西:
SomeMethod(new MemberExpression {
Expression = new ParameterExpression("x", typeof(Foo)),
Member = typeof(Foo).GetProperty("Property")
});
您可以查看生成的 IL 以了解完整的详细信息,或查看Microsoft 文档中的工作示例。涉及到一些反射(例如MemberExpressions
保持PropertyInfo
参考),但这一切都非常快。
如果您有一个您担心的应用程序,您应该对其进行分析(例如,最新版本的 Visual Studio 具有内置的性能分析器)并查看哪些特定部分运行缓慢。