is there a way to optimize below util functions that retrieves Record Type Developer Name in bulk on Trigger before insert:

public static List<Account> getAccountRecordTypeDeveloperNames(List<Account> accountList){
        Set<Id> recordIDs = new Set<Id>();
        for (Account a : accountList) {
        List<Account> accountWithRecordTypes = new List<Account>([SELECT Id, RecordType.DeveloperName FROM Account WHERE Id  IN :recordIDs]);
        return accountWithRecordTypes;

I have a similar function for when Trigger is for update as shown below:

public static Map<Id, Account> getAccountRecordTypeDeveloperNames(Map<Id, Account> accountMap){
        Map<Id,Account> accountWithRecordTypes = new Map<Id, Account>([SELECT Id, RecordType.DeveloperName FROM Account WHERE Id  IN :accountMap.keySet()]);
        return accountWithRecordTypes;


Any way to optimize both functions or combine them in my class?


There is a method exposed on the DescribeSObjectResult class, getRecordTypeInfosById(). This method allows you to access a fast, cached, SOQL-free Map without consuming limits.

You can use this method to access data on Account record types without performing an additional query. For example,

Map<Id,Schema.RecordTypeInfo> rtMap = Account.sobjectType.getDescribe().getRecordTypeInfosById();

for (Account a : myListOfAccounts) { 
    System.debug('Record type for Account ' + a.Name 
                 + ' has developer name ' + rtMap.get(a.RecordTypeId).getDeveloperName());

You can optimize both methods using this approach. Please note also that your first method, as written, won't work at all, because objects in before insert context don't have Ids.

  • getDeveloperName() -- will this count as 1 SOQL query per account inside for loop? Just wonder what happens when I have lot of accounts and if it will hit governor limits
    – user569925
    Jun 18 '18 at 16:02
  • 2
    Load the Map outside the loop for efficiency, but no, neither sourcing the Map nor accessing its contents counts as SOQL.
    – David Reed
    Jun 18 '18 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.