Loading
Scalability
ApexGuru Antipattern: SOQL Without Platform Cache

ApexGuru Antipattern: SOQL Without Platform Cache

Running the same SOQL query repeatedly during a transaction or across requests can slow down performance and put an unnecessary load on the database. Instead, use Platform Cache to eliminate the need for custom settings or persistent storage.

Scope

Detection only

Cache query results for faster data reuse across sessions or your entire org using Platform Cache. This approach is particularly helpful for frequently used queries on semistatic data invoked by various flows or trigger paths.

Detection Example

// Code without Cache
List<BranchContact__c> conlist = [SELECT Id,BillingState FROM Contact];

// Code with Cache
String cacheQuery = 'SELECT Id,BillingState FROM Contact';
conlist = BrContactPlatformCacheUtility.fetchFromCache('BrContactObjectCache', 'uid_query', cacheQuery);

// Platform Cache implementation
public class BrContactPlatformCacheUtility implements Cache.CacheBuilder {
   public static String query;
   public static String key;

   // Method to fetch from Cache
   public static List<sObject> fetchFromCache(String cacheName, String key, String query) {
      List<sObject> lstSObjValue = new List<sObject>();
      try {
         Cache.OrgPartition orgPartitionVar = Cache.Org.getPartition(cacheName);
         BrContactPlatformCacheUtility.query = query;
         BrContactPlatformCacheUtility.key = key;
         lstSObjValue = (List<sObject>)
orgPartitionVar.get(BrContactPlatformCacheUtility.class, key);
      catch (Exception ex) {
         // Handle Exception
      }
   return lstSObjValue;
   }

   // Method to Clear the Cache
   public static void clearCacheKey(String cacheName, String key) {
      Cache.OrgPartition orgPartitionVar = Cache.Org.getPartition(cacheName);
orgPartitionVar.remove(BrContactPlatformCacheUtility.class, key);
   }
}
 
Загрузка
Salesforce Help | Article