Tuesday, August 1, 2017

SOQL/DML should not be allowed to enter a FOR loop

This rule is Salesforce 101. No DML or SOQL statement should be inside for loop, even if you are running the loop for only two records.

    for(Contact c: ContactList){
    //THIS IS A NO NO NO
           account a = [Select id,name from Account where id=:c.accountid];
           c.name=c.name+a.name;
    //THIS IS A EVEN BIGGER NO
update c;  

}



The code written above is a recipe for disaster. Instead the same code can be optimized as:



for(Contact c: ContactList){
    accountSet.add(c.accountid);
}
//Whuuu huuu not inside any loop
Map<id,Account> accountMap = new Map<id,Account>([Select id,name from Account where id=: accountSet]);
for(Contact c: ContactList){
    //Like they say in treasure hunt movies, a map comes in handy.
    c.name=c.name+ accountMap.get(c.accountid).name;
}

update ContactList;



Use Collections Set, Map wherever possible:

         If in your code you have to loop inside a loop, make sure to use a map instead of a list for the inner loop. When we use a map, it is easier to fetch data and will save you a lot of time. Using map also helps speed up the code.


for(Contact c: ContactList){
    for(account a: accountList){
        if(c.accountid==a.id){
            //do something awesome
        }
    }

}

This code is good enough but can be optimized even more like this

for(Contact c: ContactList){
    if(c.accountid==accountMap.get(c.accountid)){
        //do something awesome
    }

}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.