问题
I have to use heaps of reflection in my project, like getDeclaredFields or isAnnotationPresent something like that, should I use ehcache to cache the result? will it help?
回答1:
Before adding a cache, you need to work out if you need it. Firstly, just how much can you cache and how many times can you reuse the cached objects. If things can be reused a lot and they are expensive to create, then there is an argument for a cache.
Secondly, is there a performance issue in the first place? In other words, write the code without a cache and run it. If the code is slow (and you need to define what "Slow" means to you), then again there is an argument for a cache. But if the code runs fast then adding a cache probably won't make a difference.
回答2:
As Drekka mentions it, I'd measure first indeed. That's something you should consider a general rule. Now with regards to the question at hand here, you should know that the java.lang.Class class actually already implements caching mechanism for these sort of calls. Depending on the exact access patterns, chances are very high you would not gain any performance by caching the results yourself.
来源:https://stackoverflow.com/questions/24501691/is-ehcache-faster-then-reflection-if-i-have-use-heaps-of-reflection-in-my-projec