Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use static fields to cache large objects in ASP.NET?

I've been reading up a lot lately on caching strategies for ASP.NET and my go-to method of using static fields as a cache store is never mentioned as an option. Is it a bad practice, and if so, why? Here's an example of how I would typically use it:

public static Class Repository {
    private static object _lockObject = new object();
    private static List<Products> _products = null;
    public static void GetProducts() {
        if (_products != null) { return _products; }
        lock(_lockObject) {
            _products = DAL.LoadProducts()
        }
        return products;
    }
}

The reason I prefer this pattern to say, System.Runtime.Caching.MemoryCache is because it uses no serialization and therefore scales to large objects; I have used it successfully to cache very large collections of objects from entire database tables which I then query using LINQ instead of querying the DB with SQL, resulting in massive performance gains. This pattern has served me well over a number of projects in scenarios where:

  1. I want to cache large data sets that are expensive to retrieve from storage
  2. The data will be cached for a period of hours or days and staleness is not a concern.
  3. The data be used frequently, but often uniquely filtered or transformed for a specific request.
  4. The volume of data is comfortably within the memory capacity of the host server.

Since I find this pattern so useful, I'm curious as to why the various books and tutorials on the subject don't even really discuss it as an option.

like image 480
wwarby Avatar asked Jul 29 '14 22:07

wwarby


People also ask

Are static variables cached?

Static data will cache exactly the same as any other data.

What is static cache?

Static caching is when a browser requests a resource, the server providing the resource can tell the browser how long it should temporarily store or cache the resource. For any subsequent request for that resource, the browser uses its local copy, rather than going to the network to fetch it.

How can store data in cache in ASP NET MVC?

Store data into Cache in ASP.NET MVC in ASP.NET MVC Above action method first checks for the null value in HttpContext. Cache[“MyDate”] and it its null then saves current date in the Cache. Next line simply keep the data from the Cache into ViewBag. DateTime.


2 Answers

Given that your understanding of MemoryCache is wrong, and it takes less code to store something in the MemoryCache reliably than it does a static, I don't see why you would insist on using a pattern that is error prone, leaky, and more difficult to use...

In any event, there are times when using a static to cache something is appropriate. But, in general, you should initialize statics and never change them during the life of the process. As soon as you start playing with stuff is where you will start to get pain.

like image 196
Erik Funkenbusch Avatar answered Sep 19 '22 01:09

Erik Funkenbusch


This is an old thread, but there is a simple solution to the issue of two threads doing the same work when encountering some unpopulated data cache.

public static class Repository<T>
{
    private static readonly object LockSemaphore = new object();
    private static T _dataYouWantCached;

    public static void ReadData()
    {
        if (_dataYouWantCached != null)
        {
            return _dataYouWantCached;
        }

        lock (LockSemaphore)
        {
            //This second check will prevent the "next" thread from requerying the same data that
            //the first thread populated.
            if (_dataYouWantCached != null)
                return _dataYouWantCached;

            _dataYouWantCached = SomeStaticDataAccess.LoadData();

            return _dataYouWantCached;
        }   
    }
}
like image 37
BenM Avatar answered Sep 20 '22 01:09

BenM