Increase Efficiency with Platform Cache

Platform Cache is a memory layer that stores your application's session and environment data for later access. Applications run faster because they store reusable data instead of retrieving it whenever needed. Note that Platform Cache is visible and mutable by default and should never be used as a database replacement. Developers should use cache only for static data that is either frequently needed or computationally expensive to acquire. Let's explore the use of cache in a simple Apex class.

In the example above, we acquire objects in the environment to create a schema. The Schema.getGlobalDescribe() function returns a map of all sObject names (keys) to sObject tokens (values) for the standard and custom objects defined in the environment in which we're executing the code. Unfortunately, we're not caching the data, which makes this an expensive process. This code consumes 1,307 ms of CPU time with a heap size of 80,000 bytes. Let's improve this code by using a cache partition.

This code performs the same operation but caches the result. In line 5, we're instantiating a cache partition. We're running the same function to build our schema map; however, line 15 instructs the program to place the results in the cache for later use. Our processing requirements diminished significantly, consuming only 20 ms of CPU time.

Despite the breathtaking advances in processing power, developers should always ensure they are writing efficient code that possesses a minimal processing footprint and scales with increased volume.

Further Reading

Salesforce Developer Guide - Platform Cache