Loading
Scalability
ApexGuru Antipattern: Schema.getGlobalDescribe() In a Loop

ApexGuru Antipattern: Schema.getGlobalDescribe() In a Loop

The Schema.getGlobalDescribe() method collects schema information on all SObjects, which is computationally expensive. Using Schema.getGlobalDescribe() inside a loop can lead to performance issues, including breaking governor limits.

Scope

Detection and recommendation

Detection Example

apex
public class ObjectMetadataHandler {
    
    public void processObjectNames(List<String> objectNames) {
        for (String objectName : objectNames) {
            if (Schema.getGlobalDescribe().containsKey(objectName)) {
                Schema.SObjectType sObjectType = objectMap.get(objectName);
                System.debug('Object found: ' + objectName);
            } else {
                System.debug('Object not found: ' + objectName);
            }
        }
    }
}

Recommendation

Cache the results of Schema.getGlobalDescribe() outside of the loop and reuse them within the loop.

public class ObjectMetadataHandler {
    // Cache the result of Schema.getGlobalDescribe() to avoid redundant calls
    private static Map<String, Schema.SObjectType> objectMap = Schema.getGlobalDescribe();

    public void processObjectNames(List<String> objectNames) {
        for (String objectName : objectNames) {
            // Use the cached objectMap to access SObjectType
            if (objectMap.containsKey(objectName)) {
                Schema.SObjectType sObjectType = objectMap.get(objectName);
                System.debug('Object found: ' + objectName);
            } else {
                System.debug('Object not found: ' + objectName);
            }
        }
    }
}
 
正在載入
Salesforce Help | Article