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
NeeloferNeelofer 

how to avoid apex cpu limit



List<Account> accs=new List<Account>();
account a1=new account(name='gmail',phone='123');
account a2=new account(name='fb',phone='456');
account a3=new account(name='wtsup',phone='789');
accs.add(a1);
accs.add(a2);
accs.add(a3);

List<Contact> cons=new List<Contact>();
contact c1=new contact(LastName='gmail',phone='9030');
contact c2=new contact(LastName='fb',phone='7586');
contact c3=new contact(LastName='wtsup',phone='6935');
cons.add(c1);
cons.add(c2);
cons.add(c3);

insert accs;
for(account a:accs){
    for(contact c:cons){
        if(a.Name==c.LastName){
            c.AccountId=a.Id;
        }
    }
}
insert cons;

I am getting error Apex cpu Limit Exceeded.....How to resolve this issue plz suggest me....
NagendraNagendra (Salesforce Developers) 
Hi Neelofer,

Sorry for this issue you are encountering.

Since your code execution takes a lot of time than allowed limit, try refining your code by removing unnecessary for loop, for loop inside for loop. Utilize sets, maps advantages and refine your code. Also, you can move the piece of code that does not need to be executed in the same context to the future method. 

The Maximum CPU time on the Salesforce servers - 10,000 milliseconds (Synchronous limit) 60,000 milliseconds(Asynchronous limit)
 
By doing everything mentioned above you can overcome this issue.

Hope this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra
Raj VakatiRaj Vakati
Modify code like below 
 
List<Account> accs=new List<Account>();
account a1=new account(name='gmail',phone='123');
account a2=new account(name='fb',phone='456');
account a3=new account(name='wtsup',phone='789');
accs.add(a1);
accs.add(a2);
accs.add(a3);
insert accs;


Map<String,String> accIds =new Map<String,String>();
for(Account a: [Select Id , Name from Account]){
accIds.put(a.Name,a.id);    
} 


List<Contact> cons=new List<Contact>();
contact c1=new contact(LastName='gmail',phone='9030' , AccountId =accIds.get('gmail'));
contact c2=new contact(LastName='fb',phone='7586',, AccountId =accIds.get('fb'));
contact c3=new contact(LastName='wtsup',phone='6935',, AccountId =accIds.get('wtsup'));
cons.add(c1);
cons.add(c2);
cons.add(c3);

insert cons ;