HomeDev GuideRecipesAPI Reference
Dev GuideAPI ReferenceUser GuideGitHubNuGetDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Cache read-only objects

Describes read-only object caching, and how this type of caching works.

Most APIs in Optimizely CMS return read-only instances of objects, such as IContentLoader.Get<TContentData> which returns a read-only IContent instance.

To make changes to read-only instances, create a writable clone with the CreateWritableClone method. This approach has the following advantages:

  • Reduce memory consumption – Threads serving web requests get the same instance of an object, reducing the number of short-lived objects created.
  • Improve performance – Returning shared read-only instances offers better performance.
  • Cleaner architecture – This simplifies the implementation because shared object instances cannot be changed by other threads.

Classes that support read-only implement the IReadOnly<T> interface, which is defined as follows:

public interface IReadOnly {
  void MakeReadOnly();
  bool IsReadOnly {
    get;
  }
  object CreateWritableClone();
}

public interface IReadOnly<out T>: IReadOnly {
  new T CreateWritableClone();
}

The lifecycle of a typical IContent instance is as follows:

  1. Create the IContent instance as mutable (writable).
  2. Populate the IContent instance with property values.
  3. Call the IReadOnly.MakeReadOnly method to ensure that all contained objects are made read-only. The object is immutable for the remainder of its lifetime.
  4. Add the object to the cache.