Apex CPU time limit exceeded

APEX

Salesforce has a timeout limit for transactions based on CPU usage. If transactions consume too much CPU time, they will be shut down as a long-running transaction.

What is counted

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

What is not counted

Using Map based query:-

List<Account> lstacc=[Select Id from Account limit 10000];
Set<Id> setIds=new Set<Id>();
for(Account a:lstacc){ //More CPU time for sure due to looping
setIds.add(a.id);
}

//Using Map query saves CPU time

//Fetching all account in map
Map<id,account> aMap = new Map<id,account>([Select Id,Name from Account limit 50000]);

//Creating list of accounts
List<account> accList = aMap.values() ;

//Creating set of ids

Set<id> accIds = aMap.keySet() ;

Explore if your business allows you to do the operation asynchronously:-

In some cases business process may not be real time. If there is a chance to make code execute in @future ,this will break the context and also the CPU time out limit for asynchronous process is 60 seconds(6X of synchronous process).

Aggregate SOQL usage:-

If you use normal for loop to get these, it is obvious you have spent CPU time there. Instead, try to push your calculation using SUM,AVG aggregate functions at the database layer itself. By doing this you have reduced CPU time and have pushed the process on database layer itself. Explore options to group by or create some sort of filtering at database layer. Push your calculations at database layer to reduce chances of hitting CPU time out issue.

Only take necessary data and run a loop:-

It is essential to filter only specific data while doing a for on a list of records. Too much looping will increase CPU time. The same was true when we had number of script statements limit.

uniquesymbol

Leave a Reply