Wednesday, March 16, 2011

HttpContext.Cache vs Reflection: Which is more efficient?

I'm using reflection to get the Authorize Attributes from controllers and methods.

Since I will need to get this information over and over I'm wondering if it is faster to cache it or to simply continue to use reflection to get it.

Any thoughts?

From stackoverflow
  • In general Reflection is not adviced when speed it to be attained, but you must take into account the time to develop a cache that's really working (thread safe, really fast, which gives you the current value and not an old inconsistent value) and to debug it.

    It's very difficult to tell which architecture will give the best performance, but you can easily write a little test to time the two different scenarios with a small set of simple cases. You might find that the speed is quite the same, or that it is significantly different. Either way you have your answer.

    robDean : I'm not sure I get the part of "develop a cache" since it's dealing with HttpContext.Cache. Can you explain further? Thanks.
  • Hi, this answer comes a bit late but I recently had the same thought myself for one bit in a project and ended up doing the cache using the following extension method GetOrCreate remember to lock the dictionary if you do so.

    Instead you could use an ImmutableAVLTree using a lock-free strategy

    Finally, there are some usefull utilities to use reflection here

    It's part of a full framework but you can just copy this bit of code if that's the only bit you need. Hope this helps

0 comments:

Post a Comment