使用反射与“正常”创建的类中的代码的执行时性能班级
通过反射加载的类中的代码的执行时间(运行时)性能是否与使用 new 关键字创建类时的相同代码相同?
我说是的。但我正在与一位同事讨论这个问题,他认为面向反射的代码总是较慢。
我的观点是,无论类最初是如何加载/创建的,性能都是相同的,因为 JIT 编译器不关心类是如何加载的。
我说得对吗?无论哪种方式,我都会很感激任何可以帮助澄清这一点的参考资料。
(注意:我不是在谈论使用反射创建类与使用 new 关键字创建类的性能。我指的是类创建后方法中的实际代码。)
Is the execution time (run-time) performance of code in a class that is loaded via reflection identical to the same code when the class is created using the new keyword?
I say yes. But I was discussing this with a colleague who believes that the reflection oriented code is always slower.
My view is that regardless of how the class was originally loaded/created, the performance will be identical because the JIT compiler does not care how a class was loaded.
Am I correct? Either way, I'd appreciate any references that can help clarify this.
(NB: I'm not talking about the performance of creating a class using reflection versus the new keyword. I'm referring to the actual code in methods of the class after it has been created.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于您如何执行它;-p
一旦您内部加载类型的方法,是的:常规 GIT 等通常适用(请注意,安全检查可能会使事情变得有点 /em> 如果部分受信任,则速度较慢,但不多)。
但首先您需要在动态对象上调用一些代码:
Func
,通过Delegate.CreateDelegate
),那么它将是几乎一样快,但不太方便。DynamicInvoke()
完成所有操作,它将非常像糖浆。dynamic
可能提供了一个中途之家,因为它提供了鸭子类型,并为每种类型提供了优化的缓存。那么:你如何访问它?
It depends on how you execute it ;-p
Once you're inside the methods on the loaded type, yes: regular GIT etc applies normally (note that security checks may make things a little slower if it is partially trusted, but not much).
But first you need to invoke some code on the dynamic object:
Func<string,int>
, viaDelegate.CreateDelegate
), then it will be almost as fast, but less convenient.DynamicInvoke()
, it will be pretty treacle-like.dynamic
may offer a halfway house, in that it offers duck-typing with optimised caching per type.So: how are you accessing it?
是的,一旦加载,性能是相同的。
反射的性能损失与从程序集中读取元数据有关,但执行时间将完全相同。也就是说,一旦创建了实例并且您拥有了对它的引用,它将像您拥有的任何其他类一样运行(包括 JIT 编译和所有内容)。
Yes, once loaded the performance is the same.
The performance penalty of reflection is bound to the reading of the metadata from the assembly but the execution time will be exactly the same. That is, once the instance has been created and you have a reference to it, it will behave as any other class you have (including JIT compiling and everything).
这取决于您如何使用反射。它总是比较慢,但是如果您使用 IL 发出在运行时创建工厂方法,则可以使时间差异非常小。
如果你使用简单的Activator.CreateInstance,它会慢很多。
It depends on how you use reflection. It's always slower, but you can make the time difference really small if you use IL emit to create a factory method in runtime.
If you use the simple Activator.CreateInstance, it will be so much slower.