System.LimitException: Apex CPU time limit exceeded

System.LimitException: Apex CPU time limit exceeded

The CPU Time that was introduced in Winter ’14 release. Prior to Winter’ 14, Salesforce had Script limit.

For Synchronous call, it is 10,000ms.
For the Asynchronous call, it is 60,000ms.

What contributes to CPU Time Limit:
1. Debug logs statements.
2. Library functions exposed in Apex. For example, using Describe information (Account.soObjectType.getDescribe).

3. All Apex code 

4. If DML in your code encounters a validation rule with a formula, we’ll count the time spent evaluating that formula. 

5. Workflows, Process builders and Flows execution as part of DML from Apex code.

Debugging:
1. Use Limits getCPUTime() to debug in a sandbox.

Workarounds or Solutions:
1. Use @future, Queueable Interface, or Asynchronous Apex Triggers.
2. Avoid using several debug log statements.
3. Bulkify the triggers.
4. Avoid multiple for loops.
5. Use Singleton pattern.
6. Use Double data type over Decimal for calculations.
7. Avoid Apex Library functions inside the for loop.

What is not counted?

Database operations, e.g. the portion of execution time spent in the database for DML, SOQL, and SOSL isn’t counted , nor is waiting time for Apex callouts., SOQL

CPU TIme Includes
1. Logics like if, for, statement, etc
2. Formula

CPU Time does not include
1. SOQL/Query Time
2. DML Operations(Insert, Update, etc) Time
3. Waiting for a response from a callout
4. SOSL

Synchronous CPU Time Limit: 10 Seconds
Asynchronous CPU Time limit: 60 Seconds

Reference Article:
https://help.salesforce.com/s/articleView?id=000339361&type=1

Leave a Reply