Caching in ASP.NET

I have been working on optimizing my application’s performance and wanted to share this bit of knowledge, which has dramatically improved performance: caching.

In .NET there are different ways of caching data: Session, ViewState, Application, and in Cache.

Objects that are stored in Session state are valid while the user’s session is alive. Objects that are stored in ViewState are only valid during the page’s lifecycle.

Objects that are stored in Application are valid until the Application is restarted and is available to everyone using it. The same is true for Cache.

However, Cache is the preferred method of storing application-wide data.

The Cache object is very simple to use and utilizes a key, value pair (like a dictionary or hash table).

See the code snippet below:

public List<GetAllWeekNumbersAndROD_Result> GetAllWeekNumbersAndRod()
        var applicationCache = System.Web.HttpRuntime.Cache;

         if (applicationCache["WeekNumbersAndROD"] == null)
          applicationCache.Add("WeekNumbersAndROD", _context.GetAllWeekNumbersAndROD().ToList(), null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0, 0),CacheItemPriority.Normal, null);

        return applicationCache.Get("WeekNumbersAndROD") as List<GetAllWeekNumbersAndROD_Result>;

The first line in this method is mainly so I don’t have to keep typing “System.Web.HttpRuntime.Cache” every time I want to access something in Cache. I could move this to a private property if I wanted, or make it a global (globals are bad!)

The if statement is checking for the existence of the key “WeekNumbersAndRod”. If it does not exist, it will return null.

At this point, I am adding it to cache, specifying the key, object to store in cache, cache dependency, absolute expiration, sliding expiration (in this snippet it is set to 1 day), cache item priority, and CacheItemRemovedCallback (what happens when the item  is removed from cache – I don’t want to handle that so it is set to null).

And I am simply returning the cached item as a List of GetAllWeekNumbersAndROD_Result objects (this is an EF thing).

This particular method is called as much as 900 times on page load. Before I cached it, the page took 30 seconds to load! Now, it takes 1.

Do you have any caching tips? Let us know in the comments!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s