I'm trying to cache the result of an expensive function in a MemoryCache object.
The MemoryCache requires a key that is a string, so I was wondering if it was valid to do the following:
string key = Char.ConvertFromUtf32(myObject.GetHashCode());
if (!_resourceDescriptionCache.Contains(key))
{
_resourceDescriptionCache[key] = ExpensiveFunction(myObject);
}
return (string)_resourceDescriptionCache[key];
It feels odd using a single UTF32 character as the key for a potentially large cache.
That depends.
There are many cases where using GetHashCode() could cause incorrect behavior:
A hash code is intended for efficient insertion and lookup in collections that are based on a hash table. A hash code is not a permanent value. For this reason:
http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx
If the memory cache happens (or can in the future happen) in a different process or app domain than the code that calls it, you fail the 3rd condition.
It feels odd using a single UTF32 character as the key for a potentially large cache.
If you are caching enough things, the collision rate on a 32-bit hash can be uncomfortably high due to the Birthday Problem.
When caching tens of millions of things, I have used a 64-bit hash called City Hash (created by Google, open source) with good success. You can also use a Guid, though the memory to maintain keys is twice as large for a GUID compared to a 64-bit hash.