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?
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.
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.
Reflection is slower Because it involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With