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.

有帮助吗?

解决方案

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

其他提示

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.

I would as a rule use a static field and save caching for when you need more control of the lifetime of the object. Here are two reasons I can think of right ahead:

  • There is always some overhead involved in caching the object and retrieving it from the cache, at least there will be boxing/unboxing
  • You will have to access the item by a cache key rather than directly in code, this makes the application somewhat bulkier and more difficult to understand

You should ask yourself if you need the functionality you get by caching the object, i.e. lifetime.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top