Monday, May 6, 2024

What is issue with Schema.getGlobalDescribe() and how to handle it?

 

Schema.getGlobalDescribe() is one of the costliest method in apex in term of CPU time. It gives schema of entire org. In most of orgs we have many standard and custom objects along with objects from app exchange packages. 

We generally use this method to make apex code dynamic. For example if we want to build custom apex tool like workbench which can query any object and any fields selected by user.

Most of time we use this method in Look to make sure the we find right object/Field in map. 

This put lot to load on backend CPUs and we may hit governor limit or page becomes very slow. 

To address this issue we should use Salesforce Platform Cache & Single turn pattern in apex.

Here we will call Schema.getGlobalDescribe() only once and store this in cache.

Next time whenever we need this data again we will refer it from platform cache. 


Here is sample code for your reference. 



public static Map<String, Schema.SObjectType> myGlobalDescribe() {
        Map<String, Schema.SObjectType> gd=(Map<String, Schema.SObjectType>)Cache.Org.get('local.Schema.globalDescribe');
        
if(gd==null)
        {
            gd = Schema.getGlobalDescribe();
            Cache.Org.put('local.Schema.globalDescribe', gd);
            system.debug('Cache set');
        }
        return gd;
    } 

Benefits of this approach
getGlobalDescribe() is invoked only once 
- If Org cache is empty it automatically call load schema by calling getGlobalDescribe() only once