反思是真的那么慢,我不应该使用它时,它是有道理的?我不、它是、有道理、使用它

2023-09-03 10:02:18 作者:浮生若梦

可能重复:   如何昂贵是.NET反射?

而优雅的解决方案,以一个problem我有是使用属性一类和它的属性与其他的关联。问题是,将其转换为其他的,我不得不使用反射。我正在考虑它的服务器端应用程序,将在云中托管的。

The "elegant" solution to a problem I am having is to use attributes to associate a class and its properties with another's. The problem is, to convert it to the other, I'd have to use reflection. I am considering it for a server-side app that will be hosted on the cloud.

我已经听到很多传言反映很慢,不要使用它,有多慢是慢?就那么CPU密集型的,它会加倍重视自己的CPU时间,这么多,我会从字面上来支付我的决定使用反射在我的架构上,云底?

I've heard many rumblings of "reflection is slow, don't use it," how slow is slow? Is it so CPU intensive that it'll multiply my CPU time so much that I'll literally be paying for my decision to use reflection at the bottom of my architecture on the cloud?

推荐答案

以防万一你看不到原来的问题的更新:当你反映找出所有支持某属性的类型,你有一个使用缓存的绝佳机会。这意味着你不必使用反射不止一次在运行时。

Just in case you don't see the update on the original question: when you are reflecting to find all the types that support a certain attribute, you have a perfect opportunity to use caching. That means you don't have to use reflection more than once at runtime.

要回答这个一般性问题,反思比原编译的方法调用速度较慢,但​​它是多少,比访问数据库或文件系统快得多,而且几乎所有的Web服务器做这些事情所有的时间。

To answer the general question, reflection is slower than raw compiled method calls, but it's much, much faster than accessing a database or the file system, and practically all web servers do those things all the time.