本文介绍了什么是“成本"?.NET 反射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
.NET 反射的成本是多少?

我目前处于一种编程心态,认为反射是我最好的朋友.我经常使用它来动态加载允许松散实现"而不是严格接口的内容,以及许多自定义属性.

I am currently in a programming mentality that reflection is my best friend. I use it a lot for dynamic loading of content that allows "loose implementation" rather than strict interfaces, as well as a lot of custom attributes.

使用反射的实际"成本是多少?

What is the "real" cost to using reflection?

是否值得为频繁反射的类型缓存反射,例如我们自己的 pre-LINQ DAL 对象代码对表定义的所有属性?

Is it worth the effort for frequently reflected types to have cached reflection, such as our own pre-LINQ DAL object code on all the properties to table definitions?

缓存内存占用是否会超过反射 CPU 使用率?

Would the caching memory footprint outwieght the reflection CPU usage?

推荐答案

反射需要加载和处理大量类型元数据.这会导致更大的内存开销和更慢的执行.根据这篇文章 属性修改大约慢 2.5x-3x 和方法调用速度慢 3.5-4 倍.

Reflection requires a large amount of the type metadata to be loaded and then processed. This can result in a larger memory overhead and slower execution. According to this article property modification is about 2.5x-3x slower and method invocation is 3.5x-4x slower.

这是一个很好的MSDN 文章 概述了如何使反射更快以及开销在哪里.如果您想了解更多信息,我强烈建议您阅读.

Here is an excellent MSDN article outlining how to make reflection faster and where the overhead is. I highly recommend reading if you want to learn more.

还有一个复杂的元素,反射可以添加到代码中,使其更加混乱,因此难以使用.有些人,比如 Scott Hanselman 相信通过使用反射,你经常会制造出比你解决的更多的问题.如果您的团队主要是初级开发人员,则尤其如此.

There is also an element of complexity that reflection can add to the code that makes it substantially more confusing and hence difficult to work with. Some people, like Scott Hanselman believe that by using reflection you often make more problems than you solve. This is especially the case if your teams is mostly junior devs.

如果您需要大量动态行为,最好查看 DLR(动态语言运行时).随着 .NET 4.0 中的新变化,您可能想看看是否可以将其中的一些融入到您的解决方案中.VB 和 C# 对动态的额外支持使得使用动态代码非常优雅,并且可以相当直接地创建自己的动态对象.

You may be better off looking into the DLR (Dynamic Language Runtime) if you need alot of dynamic behaviour. With the new changes coming in .NET 4.0 you may want to see if you can incorporate some of it into your solution. The added support for dynamic from VB and C# make using dynamic code very elegant and creating your own dynamic objects fairly straight forward.

祝你好运.

我在 Scott 的网站上做了更多的探索,并在反思中发现了这个 播客.我没有听过,但可能值得一听.

I did some more poking around Scott's site and found this podcast on reflection. I have not listened to it but it might be worth while.

这篇关于什么是“成本"?.NET 反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 13:47
查看更多