缓存反射属性 getter/setter 的最佳方法?
我知道反射可能会很昂贵。我有一个经常获取/设置属性的类,我想到的一种方法是以某种方式缓存反射。我不确定我是否应该缓存表达式或在这里真正做什么。这就是我目前正在做的事情:
typeof(T).GetProperty(propName).SetValue(obj, value, null);
typeof(T).GetProperty(propName).GetValue(obj, null);
那么...加快速度的最佳方法是什么?
I know that Reflection can be expensive. I have a class that gets/sets to properties often, and one way I figured was to cache the reflection somehow. I'm not sure if I'm supposed to cache an expression or what to do here really. This is what I'm currently doing:
typeof(T).GetProperty(propName).SetValue(obj, value, null);
typeof(T).GetProperty(propName).GetValue(obj, null);
So... what would be the best way to make this quicker?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该缓存结果
和
另一种可能的方法是结合 PropertyInfo .GetGetMethod 方法 (或 PropertyInfo.GetSetMethod 方法 设置器)与 Delegate.CreateDelegate 方法 并在每次需要获取/设置值时调用生成的委托。如果您需要它与泛型一起使用,您可以使用此问题中的方法: CreateDelegate 具有未知类型
与反射相比,这应该要快得多:
让反射飞翔并探索委托
还有其他方法可以更快地获取/设置值。您可以使用表达式树或 DynamicMethod 在运行时生成 il。看一下这些链接:
后期绑定调用动态方法
Delegate.CreateDelegate 与 DynamicMethod 与表达式
You should cache results of
and
Another possible approach is to combine PropertyInfo.GetGetMethod Method (or PropertyInfo.GetSetMethod Method for setter) with Delegate.CreateDelegate Method and invoke the resulting delegate every time you need to get/set values. If you need this to work with generics you can use approach from this question: CreateDelegate with unknown types
This should be much faster compared to reflection:
Making reflection fly and exploring delegates
There are also other ways to get/set values in a faster way. You can use expression trees or DynamicMethod to generate the il at runtime. Have a look at these links:
Late-Bound Invocations with DynamicMethod
Delegate.CreateDelegate vs DynamicMethod vs Expression
好吧,最简单的答案是,您可以缓存由
GetProperty
返回的PropertyInfo
对象:这将消除反射在类中重复查找属性的需要,并消除批量操作的性能打击。
Well, the simplest answer is that you could cache the
PropertyInfo
object returned byGetProperty
:That would eliminate the need for Reflection to repeatedly find the property in the class and eliminate the bulk of the performance hit.
Marc Gravell 写了一篇关于他的 HyperDescriptor 的精彩文章。
它应该提供更快的运行时反射属性访问。
Marc Gravell has written a brilliant article about his HyperDescriptor.
It should provide a much faster runtime reflective property access.
只需存储对从以下位置返回的
PropertyInfo
的引用:Just store a reference to the
PropertyInfo
that is returned from: