Implementation Differences Between Sitecore CustomCache and Generics CustomCache
There are several different ways to implement a cache in Sitecore. While your application needs may dictate a completely custom cache layer (including fully-custom management, sizing, and typing needs), Sitecore provides a couple of mechanisms for creating simple caches.
Why a Custom Cache?
Implementing a Sitecore custom cache has advantages over writing your own cache layer. First, it implements a specific abstract class and follows a common implementation pattern defined by Sitecore. Second, a custom cache is partly managed by Sitecore itself and provides rudimentry clearing capabilities via the
/sitecore/admin/cache.aspx admin page.
There are two
CustomCache classes that Sitecore makes available:
The biggest difference between these two is simple: the type of key each accepts. The first accepts only strings for keys, while the second accepts arbitrary objects (and thus potentially comes with addtional implementation complexity).
CustomCache is the easiest to use because it only accepts string keys. This is readily apparent in the class definition:
public abstract class CustomCache : CustomCache<string>
A lot of caching needs can be met by defining data based on string keys, so implementing this abstract class is the easiest for most scenarios. Using this cache boils down to something like this:
MyCustomCache.SetString("FirstName", "<p>Brandon</p>"); string cachedValue = MyCustomCache.GetString("FirstName");
The other CustomCache accepts generics, which allows developers to use other types as keys. The string-only CustomCache above actually implements this cache. The class definition reads as such:
public abstract class CustomCache<TKey>
Using objects as cache keys introduces some potential issues (for example, cache misses due to incorrect object equality comparisons). Objects as keys allows for greater flexibility in how data is cached, but be sure to implement an object's
GetHashCode overrides properly. This Stack Overflow article takes a good look at the issue.
- Cache API Changes (since Sitecore 8.2)
- How to create a custom cache in Sitecore
- Sitecore’s CustomCache – A simple implementation
- Sitecore Community Documentation: Sitecore Caching
- GitHub: CATS caching example (my own module)
Do you have questions or comments about this post? Find me on Twitter: @SitecoreSpark