[SalesForce] Trigger Error: System.LimitException: Apex CPU time limit exceeded

The below code searches on the lead record if the Account already exists in Salesforce using the website/email domain field. The code works just fine but I keep getting this error in my inbox: System.LimitException: Apex CPU time limit exceeded

Trigger Accname on Lead (before insert, before update) { 

    Account[] accts = [SELECT Name, id,Website,Domain__c FROM Account WHERE (Website != NULL OR Domain__c != NULL)];
    for(Lead l : Trigger.new)
    {        
        for(Integer i = 0; i < accts.size(); i++)
        {
            if(l.Domain__c == accts[i].Domain__c ||  l.Domain__c == accts[i].Website)
            {
                l.Account_Leads__c = accts[i].id;
                l.Account_Found__c = True;

            } else(System.debug('Not triggered.'));
        }
    }
}

Best Answer

Try at least restricting to Account records which might match, and mapping by those values.

public with sharing class LeadService
{
    public static void findAccountsByDomain(List<Lead> newRecords)
    {
        Set<String> domains = new Set<String>();
        for (Lead record : newRecords) domains.add(record.Domain__c);
        Map<String, Account> domainToAccount = new Map<String, Account>();
        for (Account record : [
            SELECT Website, Domain__c FROM Account
            WHERE Website IN :domains OR Domain__c IN :domains
        ]){
            domainToAccount.put(safeLowerCase(record.Website), record);
            domainToAccount.put(safeLowerCase(record.Domain__c), record);
        }
        domainToAccount.remove(null);

        for (Lead record : newRecords)
        {
            Account parent = domainToAccount.get(safeLowerCase(record.Domain__c));
            if (parent != null)
            {
                record.Account_Leads__c = parent.Id;
                record.Account_Found__c = true;
            }
        }
    }
    static String safeLowerCase(String input)
    {
        return input == null ? input : input.toLowerCase();
    }
}

Then in your trigger you would call LeadService.findAccountsByDomain(trigger.new);.

Note that you may have multiple records that match the same key, but you are arbitrarily choosing one. This means your code is not deterministic. You should also look up trigger handlers and find a pattern that works for you to implement logic-less triggers.

Related Topic