Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is reflection really THAT slow that I shouldn't use it when it makes sense to? [duplicate]

Possible Duplicate:
How costly is .NET reflection?

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.

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?

like image 902
Professional Sounding Name Avatar asked Mar 05 '09 20:03

Professional Sounding Name


People also ask

Is reflection really slow?

Reflection is much more slower than compiled code. There is no discussion about that but compared with other trivial operations it is not that serious. Use reflection with care and measure its impact on your code performance, if you write time-critical part of your app.

Is reflection API slow?

Adding setAccessible(true) call makes these reflection calls faster, but even then it takes 5.5 nanoseconds per call. Reflection is 104% slower than direct access (so about twice as slow). It also takes longer to warm up.

Why is reflection typically considered slow?

Reflection is slower Because it involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.

Is reflection still slow C#?

Reflection is not THAT slow. Invoking a method by reflection is about 3 times slower than the normal way. That is no problem if you do this just once or in non-critical situations.


2 Answers

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.

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.

like image 84
Daniel Earwicker Avatar answered Oct 21 '22 16:10

Daniel Earwicker


It's many times faster than filesystem access.

It's many many times faster than database access across the network.

It's many many many times faster than sending an HTTP response to the browser.

like image 31
yfeldblum Avatar answered Oct 21 '22 17:10

yfeldblum