Skip to main content

@* Salesforce Developers * 

Hi everyone,

 

I have a test class that is facing apex cpu time limit exceeded. I am trying to optimize.

 

How can I eliminate one for loop in this code?

Hi everyone,

 

I have a test class that is facing apex cpu time limit exceeded. I am trying to optimize.

 

How can I eliminate one for loop in this code?

 

for(Lead ld : leadList){           for(account a : accs){            if(ld.Company  == a.name) {             mapLds.put(ld.Id, ld) ;              ld.hasBusinessAccount__c = true;              ld.DateAddedToBusinessAccount__c = System.now();              ld.InvitedtoBusinessAccountId__c = a.Id;           }           }            } 
3 answers
  1. Dec 30, 2021, 4:25 PM

    Hey @Pauline Wambui,

     

    Try this sample code 

     

    / map to hold account name and corresponding account record

    Map < String, Account > AccountMap = new Map < String, Account > ();

    // loop through accounts and add name and account to above map

    // TO-DO Simplify the account name ex: remove the whitespace and convert it to lower case etc..

    for (account a: accs) {

    AccountMap.put(a.name, a);

    }

    for (Lead ld: leadList) {

    // if lead name contains in the account map

    // TO-DO Simplify the lead name

    if (AccountMap.get(ld.name) != NULL) {

    mapLds.put(ld.Id, ld);

    ld.hasBusinessAccount__c = true;

    ld.DateAddedToBusinessAccount__c = System.now();

    ld.InvitedtoBusinessAccountId__c = a.Id;

    }

    }

0/9000