Which is better: caching via HttpContext.Current.Cache or just static?

Last night I wrote my first IHttpModuleto handle some queries. I use a regex to validate the source URL. IHttpModulewill be called for each request, so it seems advisable to do some caching of the regular expression object to prevent it from being created on every request.

Now my question is ... which is better: use HttpContext.Current.Cacheto store the created object or for use private static Regexin my module?

I look forward to the reasons. Just to clarify: the regex will never change and thus will always be the same.

+5
source share
3 answers

If the regular expression does not change (and usually is not), then:

private static readonly Regex pattern = new Regex("...", RegexOptions.Compiled);

is the fastest and most effective in every way

+11
source

I think it depends. The built-in cache can offer you automatic expiration control, while static objects cannot. Also, if you want to change the caching mechanism (let's say you need to distribute your application), you can with the built-in cache. Static objects are just static.

+3
source

, , , . , :

  • , , , /
  • You will have to access the element using the cache key, and not directly in the code, which makes the application more cumbersome and more difficult to understand.

You should ask yourself if you need functionality that caches the object, i.e. lifetime.

+3
source

All Articles