Super Simple WCF Caching

The other day I had an interesting problem at work. My new project had a web service call that was pulling metadata off an MS SQL cube. When I started to the the project the call had 6 nested loops that it processing twice. A poster child for inefficiency. Unfortunately looping seems the be the only way to pull metadata from a cube.

By limiting the loops to only the required dimensions and processing everything only once, I was able to get the execution time from 2.5 minutes down to 6 seconds. 6 seconds is still far to long for an on demand call. Luckily the cube metadata doesn’t change frequently. Allowing me to cache the data. Taking the call from 6 seconds down to 200 milliseconds, on all subsequent calls. This is the caching I implemented for the metadata.

Created global private static instance of the HttpRuntime Cache. Allowing anyone calling the service to get the same data from the cache.

1
private static System.Web.Caching.Cache _cache = HttpRuntime.Cache;

Next, create a key to use for your cached object. Depending on the data your caching this may need to be more unique than below. Get the object from your global cache using the key. If a non-null comes out of the cache return your cached object.

1
2
3
4
5
6
7
string key = typeof(<object to cache>).Name;
 
var list = _cache.Get(key) as <object to cache>;
if (list != null)
{
      return list;
}

If no object comes out of the cache do your normal data processing. Just before you return your data add it to the cache. Here I’m caching for one day at normal priority.

1
  _cache.Add(key,<object to cache>, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);

That’s it! The first call will populate the cache and all other calls will pull from the cache. Super simple and an excellent way to improve your service call performance.

Good Luck!

I began programming in C++ when I was in college. Odd for a business major, but hey I am a Dork. After college I got a job as System Administrator. As a System Administrator I was in charge of web administration. My journey as a PHP web developer had begun. Since that time I have gained an in depth knowledge of CSS, Javascript, XML and MySQL. With changes and advances to technology I have also began learning AJAX. I started Blue Fire Development to do freelance work in my spare time.

Tagged with: , ,

1 Comment on “Super Simple WCF Caching

  1. Are concurrency issues possible when using those static variable?
    if different users try to read/write same data it could do some concurrency access.
    users are supposed to be in different threads right?

    I need to cache a quite big configuration file on a WCF web service.

Leave a Reply

Your email address will not be published. Required fields are marked *

*