0

I have a code which executes when a new contact is inserted or updated. But when i tried to insert bulk contacts through data loader, the system is throwing following error

"ContatctoAccount: System.LimitException: Apex CPU time limit exceeded".

Below is my code

trigger ContatctoAccount on Contact (after insert, after update) {

    list<Contact> Cont = new list<Contact>();
  list<Account> Acc = [select id,Account_code__c from Account where Account_code__c != Null];
    for(Contact Cnt : trigger.new){        
        if(Acc.size()>0){
            for(Account a : Acc){
                for(Contact c: trigger.new){
                    if(c.Account_code__c == a.Account_code__c){
                     c.AccountID = a.id;
                        }
                    Cont.add(c);
                }
            }
        }
    }
}

Can anyone from here please help me solving this error. Thank you in advance

1

1 Answer 1

2

You are using nested for loop in your code which can be optimized. i.e Your trigger is not bulkified. You can use the map to solve your problem.

You are running unnecessarily for loop in your code. Assuming that Account_code__c is a text field and it is unique for each account, try this:-

trigger ContatctoAccount on Contact (after insert, after update) {

    list<Contact> Cont = new list<Contact>();
    Map<String,Account> mapCodeWithAccount = new Map<String,Account>();
    for(Account acc: [select id,Account_code__c from Account where Account_code__c != Null]){
        if(acc.Account_code__c!= null){
            mapCodeWithAccount.put(acc.Account_code__c, acc);
        }
    }
    for(Contact C : trigger.new){
        if(mapCodeWithAccount.containsKey(c.Account_code__c)){
            c.AccountID = mapCodeWithAccount.get(c.Account_code__c).id;
            Cont.add(c);
        }
    }
}

Generally what happens is Salesforce has a timeout limit for transactions based on CPU usage. If transactions consume too much CPU time, we'll shut them down as a long-running transaction.

What's counted:-

  • All Apex code
  • Library functions exposed in Apex
  • Workflow execution

While writing an apex code, always follows the best practice. You can find them here:-

"Apex Code Best Practices"

and here:- Code more efficiently to avoid 'Apex CPU time limit exceeded'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .