Loading
システム管理者に対するフィッシング耐性MFA・全従業員ユーザーMFAの適用のお知らせ 続きを読む
ただいま大変多くのお問い合わせをいただいており、ご連絡までにお時間を頂戴しております続きを読む
Scalability
ApexGuru Antipattern: Schema.getGlobalDescribe() Called Multiple Times Within a Class

ApexGuru Antipattern: Schema.getGlobalDescribe() Called Multiple Times Within a Class

Multiple calls to Schema.getGlobalDescribe() in a class cause performance issues and are computationally expensive. Calling this method multiple times within the same method results in redundant schema retrieval. Increased CPU usage can cause you to go over your governor limits.

Scope

Detection and recommendation

Detection Example

public void pro(String objectName) {
    
    // Get the describe result for the provided object name
    Schema.DescribeSObjectResult describeResult = Schema.getGlobalDescribe().get(objectName).getDescribe();
    
    // Log object label and plural label
    System.debug('Object Label: ' + describeResult.getLabel());
    System.debug('Object Plural Label: ' + describeResult.getLabelPlural());

    // Dynamically create a new instance of the SObject
    SObject newRecord = Schema.getGlobalDescribe().get(objectName).newSObject();
    
    newRecord.put('Name', 'Address');
    
    // Insert the record
    insert newRecord;
    
    // Log the newly created record ID
    System.debug('New record created with ID: ' + newRecord.Id);
}
}

Recommendation

When you optimize logic design, avoid multiple Schema.getGlobalDescribe() calls. Focus on optimizing the functionality itself. Use alternatives like caching or metadata to eliminate the need for these calls. Retrieve schema information one time at the start of the method and reuse it to improve performance.

public void getObjectDescribe(String objectName) {    
    // Get the describe result for the provided object name
    Schema.DescribeSObjectResult describeResult = null
    try {
         List<Schema.DescribeSObjectResult> describes = Schema.describeSObjects(new String[] { objName}, SObjectDescribeOptions.DEFERRED);
         result = describes[0];
     } catch (InvalidParameterValueException ipve) {
          result = null;
     }
     Schema.DescribeSObjectResult objectResult = result;
    
    // Log object label and plural label
    
    if (objectResult != null) {
        System.debug('Object Label: ' + describeResult.getLabel());
        System.debug('Object Plural Label: ' + describeResult.getLabelPlural());
    }

    // Dynamically create a new instance of the SObject
    SObject newRecord = (SObject)Type.forName( objectName ).newInstance()
    
    newRecord.put('Name', 'Address');
    
    // Insert the record
    insert newRecord;
    
    // Log the newly created record ID
    System.debug('New record created with ID: ' + newRecord.Id);
}
 
読み込み中
Salesforce Help | Article