function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Aaron HillAaron Hill 

Refactoring Code after "Apex CPU time limit exceeded:-"

We have a lead/account relationship. I created a lead field called "Related Account", which is a lookup field. The lead is then added to a related list in the account view. I wrote the following so that when a lead was updated, the related account trigger would automatically find the matching account and populate the field with that information. It works great on an indiviual basis but not at all when I try to bulk update more than a handful of leads. The full error is:

"CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:updateRelatedAccount: System.LimitException: Apex CPU time limit exceeded:--".

My question: can this code be refactored so that it works for bulk updates? And if so, how?

Thanks for your time.

 
trigger updateRelatedAccount on Lead (before update) {
    List<Account> accList = [SELECT Id, Name FROM Account];
    
    for (Lead lead : System.Trigger.new) {
        for (Account acc : accList) {
            if (lead.Company != '' && lead.Company == acc.Name) {
                lead.Related_Account__c = acc.Id;
            }
        }
    }
}

 
Best Answer chosen by Aaron Hill
venkat-Dvenkat-D
Try below code

set<string> accNames = new set<string>();
for(Lead ld : Trigger.New){
accNames.add(ld.Company);
}

list<Account> accs = new list<Account>([Select Id,Name from account where name=:accNames]);
map<String,id> mapaccs = new map<String,id>();

for(Account ac : accs){
mapaccs.put(ac.Name,ac.Id)
}

for(Lead lds : Trigger.New){
lds.related_account__c = mapaccs.get(lds.company).Id;
}

All Answers

venkat-Dvenkat-D
Try below code

set<string> accNames = new set<string>();
for(Lead ld : Trigger.New){
accNames.add(ld.Company);
}

list<Account> accs = new list<Account>([Select Id,Name from account where name=:accNames]);
map<String,id> mapaccs = new map<String,id>();

for(Account ac : accs){
mapaccs.put(ac.Name,ac.Id)
}

for(Lead lds : Trigger.New){
lds.related_account__c = mapaccs.get(lds.company).Id;
}
This was selected as the best answer
Aaron HillAaron Hill
@Venky409 

I recieved the following error: "Initial term of field expression must be a concrete SObject: Id" 

For line 15
venkat-Dvenkat-D
lds.related_account__c = mapaccs.get(lds.company);
Aaron HillAaron Hill
Works great with that change- thanks!
 
venkat-Dvenkat-D
Just to avoid null pointer exceptions you can change last three lines to below. Its always better to query required records in SOQL

for(Lead lds : Trigger.New){
if(mapaccs.containskey(lds.compamy)){
lds.related_account__c = mapaccs.get(lds.company).Id;
}
}
Aaron HillAaron Hill
I'll add that, thanks!