Jaffer Ali, an Advanced Salesforce Developer gave Talent Hub an overview of how to effectively use Platform Cache in Salesforce. Jaffer has over 5 years Salesforce Development experience and has worked in Pakistan, Dubai and now Australia.
Cache layer is one of the very cool features now available in Apex. Earlier developers used to utilise View State, Custom setting or object, to store dataset. All these approaches require lots of overhead to recalculate dataset or it has limits to store complex structures.
Now, with the help of Cache a slice of space is available in application, which offers a built in way to interact with stored data set.
There are two types of Cache, which are present as follows:
Available for each individual user using the application. Performance can be improved when a large data structure needs to be used throughout the application.
In field service solution when it is required to calculate valid SLA for each user who logged in to portal. In this case SLA result can be stored in the cache to reuse it again throughout the application without recalculating it each time again and again.
Org cache is the shared cache for complete organisation. Common dataset, which is required by multiple users can store in this type of Cache. For example navigation bar based on each profile can be stored in Org Cache.
The best practice is to use cache to store data, which is not required to change in a session.
In order to play with this feature; it should be requested from Salesforce Support in Developer organisation.
Below is the simple code to add and get a variable from the cache.