DanP
DanP

Reputation: 6478

General strategy for caching "random" data

I have a website that needs to display a "random" selection of items on its homepage. This list is somewhat expensive to generate, so I would like to look into performing some caching that still allows the listing to still appear somewhat random to the untrained eye.

My idea was to use a randomly-chosen number within a given range (let's say 10, for argument's sake) as part of the cache key. Psuedo code would look something like this:

randomCacheVariation = (random number between 1 and 10)

cacheKey = "myRandomList_" + randomCacheVariation

If cache.contains(cacheKey) Then   
     return existing random list 
Else  
     generate new radom list   
     add to cache  
     return list 
End If

Does anyone have a better suggestion for how something like this should be implemented?

Update:

Just to be clear, I'm not looking for implementations of caching services, but a strategy of how to cache pseudo-random data by storing some finite number of variations of my list in the cache.

Upvotes: 1

Views: 521

Answers (2)

Chad Moran
Chad Moran

Reputation: 12854

This is in C# but...

public static class Cache
{
    public void Add<T>(string key, T item)
    {
        HttpRuntime.Cache[key] = item;
    }

    public T Get<T>(string key, Func<T> valueFactory)
    {
        var obj = HttpRuntime.Cache[key];

        if (obj == null)
        {
            if (valueFactory != null)
            {
                T tObj = valueFactory();

                Add(key, tObj);

                return tObj;
            }

            return default(T);
        }

        return (T)obj;
    }
}

And then you can use it like this...

var randomSet = Cache.Get<string>("RandomResultSet", () => {
    // pull down large random result-set
    var randomSet = do stuff;
    return randomSet;
});

// Now that we have a large result set cached, let's select a smaller one
var randomStuff = randomSet.GetSmallerRandomSet();

Upvotes: 0

Nelson Rothermel
Nelson Rothermel

Reputation: 9746

Can you generate a "random" list on app startup with maybe 100 items? Then if you need to display 10 "random" items, randomly select from the 100.

Supporting documentation: https://stackoverflow.com/questions/462219/xkcd-random-number

Upvotes: 1

Related Questions