8

What are the main pros and cons for using HttpRuntime Cache against using simple static field?

I need to store data in scope of entire ASP.NET application.

HttpRuntime.Cache["MyData"] = someHashtable;

vs.

private static System.Collections.Hashtable _myData;
public static System.Collections.Hashtable MyData
{
    get
    {
        if (_myData == null)
        {
            _myData = new System.Collections.Hashtable();
            // TODO: Load data
        }
        return _myData;
    }
}
Radek Stromský
  • 838
  • 3
  • 12
  • 27

3 Answers3

5

Objects in HttpRuntime.Cache have unknown expiry periods unless explicitly set (meaning that objects can expire any time), whereas objects within your HashTable live for as your application pool is alive (unless you manually remove an entry). The HttpRuntime.Cache also allows you to set various other characteristics, such as (optional) cache item priority and expiry time.

foxy
  • 7,599
  • 2
  • 30
  • 34
  • 1
    The thing I was worry about when using `HttpRuntime.Cache` are conflicts of the keys, when you have large enterprise application with larger amount of cached data. But as I see it, `HttpRuntime.Cache` has one more brilliant feature in addition to priority and expiration time. **CacheDependencies**. So even when I want to have cached data that never expires, it will eventually change and this change can be handled by cache dependecies (hopefully). – Radek Stromský Aug 04 '11 at 06:10
0

HttpRuntime.Cache allows you to specify expiration callback, but with static dictionary you will have to wait for a query to run your expiration loop of your cache items.

alpav
  • 2,972
  • 3
  • 37
  • 47
0

with the cache you can easily set an enddate to the validity; the cache object expires the content automaticly.

also the cache can be given a priority, that less important items can be given a low priority so when the server gets high load, that item is removed first

with cahce however you allways have to do some extra effort in your unit test because the httpcontext isn't available during unit tests.

Michel
  • 23,085
  • 46
  • 152
  • 242
  • `HttpContext` makes me a headache. Fortunatelly, this is not the case. `HttpRuntime.Cache` is accessible even in unit tests. But it doesn't have to be fully functional since [here](http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx) they say not to use it outside of ASP.NET applications. – Radek Stromský Aug 04 '11 at 06:29