In caching systems such as Redis/MemCache one needs to serialize and deserialize objects. When storing objects, one serializes, and when accessing that object one needs to deserialize.
Does C#/.Net MemCache also need to serialize/desrialize objects? e.g. when I store an object of the following class, is only the object reference set in cache, OR the object is serialized before storing in Cache? Tests suggest that the cache is storing just a reference. But I wanted to check.
class CacheData
{
public int A = 0;
public int B = 0;
}
private static void TestMemoryCache()
{
CacheData origObject = new CacheData();
ObjectCache cache = MemoryCache.Default;
CacheItemPolicy policy = new CacheItemPolicy();
cache.Set("someKey", origObject, policy);
origObject.A = 2;
origObject.B = 3;
CacheData cachedObj = cache["someKey"] as CacheData;
if (cachedObj == origObject)
Console.WriteLine("Same");
else
Console.WriteLine("Distinct");
cachedObj.A = 5555;
cachedObj = cache["someKey"] as CacheData;
Console.WriteLine("The A value is: " + cachedObj.A);
}
I couldn't immediately find anything in the documentation that specifically states whether objects are serialized or not, unless that is what they mean by calling it an "object cache". In practice objects are not serialized, and are just held in memory as-is.
You can verify this behavior by reading the reference source. While the current implementation is not a guarantee of behavior in the future, changing the implementation to use serialization could potentially break things in so many ways that I think it's safe to say it's not going to change.
Relevant reference source links:
https://github.com/Microsoft/referencesource/blob/master/System.Runtime.Caching/System/Caching/MemoryCache.cs
https://github.com/Microsoft/referencesource/blob/master/System.Runtime.Caching/System/Caching/MemoryCacheStore.cs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With