c# - Does it make sense to use an object hash code as a memory cache key? -
I am trying to cache the result of an expensive function in the MemoryCap object.
Memory cache is a string that requires a key, so I was thinking that it was valid for the following:
string key = char.ConvertFromUtf32 (myObject .GetHashCode ()); If (! _resourceDescriptionCache.Contains (key)) {_resourceDescriptionCache [key] = expensive work (myObject); } Return (string) _resourceDescriptionCache [key]; This seems strange to any UTF 32 character as a key for a potentially large cache.
It depends.
There are many cases where using GetHashCode () may be inaccurate behavior:
The purpose of a hash code is to look at efficient entry and collection that is a hash A hash code is not a permanent value based on the table for this reason:
- Do not serial the hash code values or store them in the database.
- Do not use the hash code to retrieve an object from a key store.
- Do not send the hash code to application domains or processes In some cases, hash codes can be calculated on a per-process or per-application domain basis.
If the memory cache occurs (or may be in the future) in a different process or app domain than the code that calls you You fail in the third position.
This sounds like a single utf 32 character as a key for a potentially large cache. / p>
If you are caching enough things, the collision rate on 32-bit hash may be uncomfortably high.
When tens of millions of things are cached, I have used 64-bit hash (made by Google, open source) with good success, you can also use a guide. , Though memory memory is doubled for the GUID compared to 64-bit hash.
Comments
Post a Comment