-1

I am getting error

System.LimitException: Apex CPU time limit exceeded

It is working fine in sandbox once i deploy in production it gave me error as above.

As in production i got

set<String> unqName = new Set<String>();
List<Account> actLst = new List<Account>();
Map<String,List<Account>> act = new Map<String,List<Account>>(); // add list item to map

for(Account a:[SELECT Id,Name,duplicate__c FROM Account where Id In (Select Account_Name__c FROM Opportunity__c)])
{
    unqName.add(a.Name);
}

for(Account a:[SELECT Id,Name,duplicate__c FROM Account where Id In (Select AccountId FROM Contact)])
{
    unqName.add(a.Name);
}

List<AggregateResult> acc=[SELECT Name accname,  Prospect_Code__c  , COUNT(Id) ids FROM Account where Id Not
                           In (Select Account_Name__c FROM Opportunity__c) And Id Not In (Select AccountId FROM Contact)                           
                           GROUP BY Name, Prospect_Code__c  HAVING count(Id)>1];

List<Account> accList = [SELECT Id,Name,duplicate__c FROM Account where Id Not
                           In (Select AccountId from Contact) And Id Not In (Select Account_Name__c FROM Opportunity__c)];

for(Account acc : accList)
{
    if(!act.containsKey(acc.Name))
        {
            act.put(acc.Name,new List<Account>{acc});
        }
    else 
        {
            act.get(acc.Name).add(acc);
           // System.debug(act.get(acc.Name));
        }

}

System.debug('Name' + unqName);

for(String tmp : act.keySet()){
    for(String s:unqName){
        if(s!=tmp){
            for(Account a:act.get(tmp)){
                if(act.get(tmp).indexOf(a) != 0)     //error comes over here
                {
                    a.duplicate__c = True;
                    actLst.add(a);
                }
            }
        }
        else{
            for(Account a:act.get(s)){         
                    a.duplicate__c = True;
                    actLst.add(a);
            }
        }
    }
}

System.debug(' actLst size '+ actLst.size());

        if(!actLst.isEmpty()){
            update accList;
            System.debug('accList size ' + actLst.size());
            System.debug('accList ' + actLst);
        }
3

I think you have some large data sets in prod which are exposing some issues. In your case, I think you're querying for all accounts, and on 3 occasions querying for all your contacts and opps as well. Also, you have 3 nested for loops. Cubes like that take time.

Having said that, it seems like the goal of your code is to check which accounts are duplicates. Duplicate Rules do exactly this without using code. https://help.salesforce.com/articleView?id=duplicate_rules_map_of_reference.htm&type=5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.