Search code examples
c#.netjsoncachingcachemanager

Should I cache json, Bson or JObject in the ICacheManager?


I have some JObjects which I need to cache, and I wonder what best practice is when caching such data in CacheManager?

I'm concerned with

  1. Using a reasonably small amount of memory in the cache.
  2. Not unnecessarily serialize to avoid useless processing.

If I cache the json string I need to parse it every time I read the cache.

If I cache the JObject I don't know how it will be serialized to the cache. Probably as a non-compact binary array. But I won't have to do anything to it after retrieving it.

That's why I'm considering that perhaps it will serialize Bson better, or maybe that's going to simply add another layer of serialization? After all, I'll have to convert the Bson to JObject when reading the cache, much like if I were to cache the json string.


Solution

  • I pursued this on github where, long story short, I ended up caching the json string and JObject.Parse it on retrieval.

    The pertinent question to ask was "are you using a distributed cache?" I am, and I'm also using a local cache.

    If I was only using a local cache, I could put the JObjects straight in the cache as no serialization is involved.

    When using a distributed cache however, you actually cannot place a JObject into it since that type isn't serializable (no SerializableAttribute).

    When using both, you're constrained by the requirements of both, meaning you're left with caching the json strings and parsing them on retrieval.

    It is possible that one could use the CacheManager.Serialization.Json package to swap out the serialization mechanism. But I'd rather keep the binary serializer in my scenario as I'm mostly caching POCO's and a binary serializer should be more efficient in general. I don't think using this would net me any performance gains anyway, since the built-in serializer would have to transform the JObjects to json internally anyway.

    In conclusion: By keeping the binary serializer and caching the json as strings I don't lose out on performance, but I do have to add a few JObject.Parse(..) here and there when reading from the cache. With decent encapsulation, that's not an issue.