Loading
Scalability
ApexGuru Antipattern: SObject Map in a For Loop

ApexGuru Antipattern: SObject Map in a For Loop

Building Map<Id, sObject> in a For loop inserts one record at a time. This query fetches all Custom Object__c records without filtering, which causes extra CPU usage. Filtering later in Apex boosts memory use, risks overflow, and slows performance. Instead, use Apex's map constructor or putAll().

Scope

Detection and recommendation

Detection Example

This code manually loops through each sObject and inserts it into the map using put(), which adds unnecessary CPU overhead.

Map<Id, Account> accMap = new Map<Id, Account>();
for (Account acc : [SELECT Id, Name FROM Account]) {
    accMap.put(acc.Id, acc);
}

Recommendation

Increase map creation efficiency by using list constructor.

List<Account> accs = [SELECT Id, Name FROM Account];
Map<Id, Account> accMap = new Map<Id, Account>(accs);

If you’re working with large results or paginated queries, use putAll() outside of the loop.

Map<Id, Account> accMap = new Map<Id, Account>();
for (List<Account> accs : [SELECT Id, Name FROM Account]) {
    accMap.putAll(accs);
}
 
Indlæser
Salesforce Help | Article