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
Ramesh VaratharajRamesh Varatharaj 

System.LimitException: Apex CPU time limit exceeded on trigger

Hello Experts, need assistance to trace the issue. I am using the below code to map lead records to account - recently i am noticing System.LimitException thrown for this code. I am not able to trace the inefficiency - any clue is appreciated. Thanks

trigger addAccountv1 on Lead (before Insert,before Update){

//sting list to hold leads company name and domain details...
List<string> companies=new list<string>();
List<String> domains =new List<String>();
//list to hold all leads invoking trigger....
List<Lead> leadstomapaccount = new List<Lead>();

For (lead l:trigger.new)
{
  companies.add(l.company);
  domains.add(l.DomainGeo__c);
  leadstomapaccount.add(l);
 }

//querry account where company name of domain matached the lead record and update the list
List<Account> leadAccountIds=[Select Id, OwnerId,Domainv1__c, Name FROM Account WHERE Name IN: companies OR Domainv1__c IN:domains ];


Map<String, Id> acctNameId=new Map<String, Id>();
Map<String, Id> acctDomain=new Map<String, Id>();

//create a map of account id and name. same for account id and domain

For (Account a:leadAccountIds){
  acctNameId.put(a.name,a.Id);
  acctDomain.put(a.Domainv1__c,a.Id);
}



if(Trigger.isInsert) {
For (Lead l2:leadstomapaccount ){ 
  if(acctDomain.containsKey(l2.DomainGeo__c)){  
    l2.Account__c=acctDomain.get(l2.DomainGeo__c);   
  }
    if(acctDomain.containsKey(l2.DomainGeo__c) == false && acctNameId.containsKey(l2.company) ){
    l2.Account__c=acctNameId.get(l2.company);
 }
 
 
}
}

else {

For (Lead l2:leadstomapaccount  ){
   if(l2.Account__c == null){ 
  if(acctDomain.containsKey(l2.DomainGeo__c)) {
    l2.Account__c=acctDomain.get(l2.DomainGeo__c);   
  }
  
  if(acctDomain.containsKey(l2.DomainGeo__c) == false && acctNameId.containsKey(l2.company) ){
    l2.Account__c=acctNameId.get(l2.company);
 }
   }
 
 }
}
}
Dileep KumarDileep Kumar

Hi Ramesh,

Here is your code :List<Lead> leadstomapaccount = new List<Lead>();.This is wrong .

Please use this code inplace of above line 

List<Lead> leadstomapaccount ;

Now try and let me know

Thanks,

Dileep

Shweta_AgarwalShweta_Agarwal
Hi Ramesh,

Can you check if there is any recursion in your trigger.

Thnaks,
Shweta
Ramesh VaratharajRamesh Varatharaj
Hi Dileep, thanks - but this does not seem to fix the issue. I am still getting the limit exception periodically - also can you please help with the difference in 2 list definitions - both works the same way right?
List<Lead> leadstomapaccount = new List<Lead>();
vs List<Lead> leadstomapaccount ;