If we have a scenario of comparing two different lists and performing a logic it works like a Odo meter of the car. The Inner loop executes first and outer loop is executed later. Consider the scenario of comparing two different lists and doing a field update based on the comparison.
Lets take two different lists
List<account>accountlist=[select id, name from account limit 9999];
List<customobject>customobjList=[select id, textvalue, lookupaccount from custom object limit 9999];
based on the text value of a field from a custom object the logic should fetch the related account name and update the look up field in the custom object.
This scenario can be achieved as follows
for(customobjList obj:customobjList){
for(Account a:accountlist){
obj.textvalue=a.name;
}
}
In triggers the code needs to be properly bulkifie
The above piece of code will work fine. But the list defined inside the inner for loop will soon hit the governor limits before we can expect.
How to avoid this?
By making proper usage of Salesforce Collections
The below code will also perform the same logic but it handles the governor limits very well
list<account>acc=[select id,name from account limit 9999];
map<string,account>accfinalmap=new map<string,account>();
for(account acc1:acc){
accfinalmap.put(acc1.name,acc1);
}
for(customobject sa3:trigger.new){
if(accfinalmap.containskey(sa3.textvalue)){
sa3.lookupaccount =accfinal.id;
}
}
By making use of the Collection times effectively we can control the governor limits at ease.
Authored by: Nirmal Christopher,
Technical Consultant,
Global Tech & Resources, Inc. (GTR).
No comments:
Post a Comment