Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better: caching through HttpContext.Current.Cache or just a static?

Last night I wrote up my first IHttpModule to do some request processing. I'm using a regular expression to inspect the raw url. The IHttpModule will be called on every request, so it seems reasonable to do some sort of caching of the regular expression object to prevent creation of it on every request.

Now my question... what is better: use the HttpContext.Current.Cache to store the instantiated object or to use a private static Regex in my module?

I'm looking forward to the reasons why. Just to clarify: the regex will never change and thus always be the same thing.

like image 423
Kees C. Bakker Avatar asked Mar 28 '11 21:03

Kees C. Bakker


2 Answers

If the regex isn't going to change (and it usually isn't), then:

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

is the fastest and most efficient in every way

like image 150
Marc Gravell Avatar answered Nov 15 '22 05:11

Marc Gravell


I guess it depends. Built in cache can offer you automatic expiration control while static objects can't. Also, if you want to change the cache mechanism (let's say you have to distribute your applicaiton) you can with built in cache. Static objects are just it, static.

like image 21
tucaz Avatar answered Nov 15 '22 03:11

tucaz