32

Long time listener - first time caller. I am hoping to get some advice. I have been reading about caching in .net - both with System.Web.Caching and System.Runtime.Caching. I am wondering what additional benefits I can get vs simply creating a static variable with locking. My current (simple minded) caching method is like this:

public class Cache
{
    private static List<Category> _allCategories;
    private static readonly object _lockObject = new object();

    public static List<Category> AllCategories
    {
        get
        {
            lock (_lockObject)
            {
                if (_allCategories == null)
                {
                    _allCategories = //DB CALL TO POPULATE
                }
            }
            return _allCategories;
        }
    }
}

Other than expiration (and I wouldn't want this to expire) I am at a loss to see what the benefit of using the built in caching are.

Maybe there are benefits for more complex caching scenarios that don't apply to me - or maybe I am just missing something (would not be the first time).

So, what is the advantage of using cache if I want a cache that never expires? Doesn't static variables do this?

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
sfsr
  • 1,091
  • 1
  • 10
  • 9
  • I think your lock block should include the if statement. Else you may get the case where it still loads from the db more than once. – row1 May 13 '11 at 01:52
  • 1
    You are right - sorry - was a little to hasty in writing up a simple example. I have changed it in the original question. – sfsr May 13 '11 at 01:57

3 Answers3

24

First of all, Xaqron makes a good point that what you're talking about probably doesn't qualify as caching. It's really just a lazily-loaded globally-accessible variable. That's fine: as a practical programmer, there's no point bending over backward to implement full-on caching where it's not really beneficial. If you're going to use this approach, though, you might as well be Lazy and let .NET 4 do the heavy lifting:

private static Lazy<IEnumerable<Category>> _allCategories
    = new Lazy<IEnumerable<Category>>(() => /* Db call to populate */);

public static IEnumerable<Category> AllCategories 
{ 
    get { return _allCategories.Value; } 
}

I took the liberty of changing the type to IEnumerable<Category> to prevent callers from thinking they can add to this list.

That said, any time you're accessing a public static member, you're missing out on a lot of flexibility that Object-Oriented Programming has to offer. I'd personally recommend that you:

  1. Rename the class to CategoryRepository (or something like that),
  2. Make this class implement an ICategoryRepository interface, with a GetAllCategories() method on the interface, and
  3. Have this interface be constructor-injected into any classes that need it.

This approach will make it possible for you to unit test classes that are supposed to do things with all the categories, with full control over which "categories" are tested, and without the need for a database call.

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • 1
    I agree that "cache" may not be the correct word - but "lazily-loaded globally-accessible variable" doesn't roll off the tounge quite the same :) I hadn't heard of Lazy before and I will be using it whenever I need a lazy loaded variable now. – sfsr May 13 '11 at 14:40
23

System.Runtime.Caching and System.Web.Caching have automatic expiration control, that can be based on file-changes, SQL Server DB changes, and you can implement your own "changes provider". You can even create dependecies between cache entries.

See this link to know more about the System.Caching namespace:

http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx

All of the features I have mentioned are documented in the link.

Using static variables, would require manual control of expiration, and you would have to use file system watchers and others that are provided in the caching namespace.

Miguel Angelo
  • 23,796
  • 16
  • 59
  • 82
  • 2
    Wow - you guys are fast :) That is a great point. I can totally see the need for that in more complex situations - but assuming the category list in the original question is a fixed list (meaning changes will be very rare), and I don't want it to expire - I assume the additional overhead needed to maintain that expiration control would actually be a vote for using static variables since they would be more performant in this case. BTW - I want to have this discussion and want to dig into these types of things - I am not trying to be stubborn - just making the case on the other side. – sfsr May 13 '11 at 02:03
  • 3
    I think that you should not tie yourself to frameworks if you don't need their services. If you don't need expiration control, nor the other services of the caching system, then don't use it. But if you need, do not reinvent the wheel. Thats of course my point of view! Some may disagree. – Miguel Angelo May 13 '11 at 02:09
  • I think it is a perfectly valid solution to use static variables in the case you provided. =) – Miguel Angelo May 13 '11 at 02:10
4

Other than expiration (and I wouldn't want this to expire) ...

If you don't care about the life-time the name is not caching anymore.

Still using Application (your case) and Session object are best practices for storing application level and session level data.

Xaqron
  • 29,931
  • 42
  • 140
  • 205
  • 1
    I think you are right about cache not being the right word - I just meant it in the sense that the DB results are kept in local memory rather than having to go to the slower medium each time they are needed. As for Application object - I have to disagree about that. The MSDN article quoted here [link](http://stackoverflow.com/questions/303725/asp-net-application-state-vs-a-static-object/303787#303787) says that it is more for classic asp migration. – sfsr May 13 '11 at 14:45
  • ASP classic is based on modular programming. So for communicating between modules Application scope variables (like C) was the option. You are loading Categories from db to memory for fast access. If you expect changes to db that reflect Categories you need update your cache class based on some criteria (time, trigger...) and then it would be a cache by meaning. Caching is more about heavy and lengthy operations i.e. when you see drive used and free space in my computer. On a stock market website, it is not wise to calculate one year changes for each request. You can do it once daily. – Xaqron Mar 28 '13 at 19:32