JohnB
JohnB

Reputation: 13723

Caching function results

Suppose I have some function Func<int,int,int>. Now I want to cache (and quickly lookup) function results.

Requirements:

  1. Fixed cache size (say, e.g., 1000 triples (input, input, result)).
  2. Fast lookup and fast storage in cache.
  3. If the cache is full, the entries not accessed (looked up) for the longest time should be deleted.

What kind of data structure should be used?

Upvotes: 1

Views: 105

Answers (1)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28728

Use the .NET Cache, or use the MemoryCache, which is a non-web specific cache.

You are able to specify the amount of memory that can be used by the cache using the CacheMemoryLimit property.

When the cache is full you can Trim a desired percentage of entries, and the entries will be removed as desired:

... entries will be removed from the cache based on a least-recently used (LRU) algorithm until the requested trim percentage is reached

The key for each item in the cache needs to be a string, so I'd format your input as {0}-{1} or similar. You might want to perform some performance testing to satisfy your requirement but I am confident that this will be as fast as any other solution.

Upvotes: 1

Related Questions