Thursday, 13 March 2025

𝗔𝘃𝗼𝗶𝗱 𝗖𝗣𝗨 𝗧𝗶𝗺𝗲 𝗟𝗶𝗺𝗶𝘁𝘀 𝗶𝗻 𝗔𝗽𝗲𝘅

 Ever faced the dreaded "𝗔𝗽𝗲𝘅 𝗖𝗣𝗨 𝘁𝗶𝗺𝗲 𝗹𝗶𝗺𝗶𝘁 𝗲𝘅𝗰𝗲𝗲𝗱𝗲𝗱" error? 

Salesforce enforces a 𝟭𝟬-𝘀𝗲𝗰𝗼𝗻𝗱 𝗖𝗣𝗨 𝘁𝗶𝗺𝗲 𝗹𝗶𝗺𝗶𝘁 𝗽𝗲𝗿 𝘁𝗿𝗮𝗻𝘀𝗮𝗰𝘁𝗶𝗼𝗻, and hitting it can crash your process.


Here are 𝟱 𝗣𝗿𝗼 𝗧𝗶𝗽𝘀 to optimize CPU usage in Apex:


𝟭. 𝗔𝘃𝗼𝗶𝗱 𝗡𝗲𝘀𝘁𝗲𝗱 𝗟𝗼𝗼𝗽𝘀 

Looping inside another loop can skyrocket CPU usage. Instead, use 𝗺𝗮𝗽𝘀 and 𝘀𝗲𝘁𝘀 for efficient lookups.


𝟮. 𝗨𝘀𝗲 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗶𝗼𝗻𝘀 𝗘𝗳𝗳𝗶𝗰𝗶𝗲𝗻𝘁𝗹𝘆 

Instead of multiple SOQL queries inside a loop, 𝗾𝘂𝗲𝗿𝘆 𝗼𝗻𝗰𝗲 and process data in bulk using 𝗟𝗶𝘀𝘁𝘀 or 𝗠𝗮𝗽𝘀.


𝟯. 𝗥𝗲𝗱𝘂𝗰𝗲 𝗖𝗼𝗺𝗽𝗹𝗲𝘅 𝗖𝗮𝗹𝗰𝘂𝗹𝗮𝘁𝗶𝗼𝗻𝘀 

Break down complex logic, cache repetitive computations, and use 𝗹𝗮𝘇𝘆 𝗹𝗼𝗮𝗱𝗶𝗻𝗴 where possible.


𝟰. 𝗣𝗿𝗲𝗳𝗲𝗿 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗶𝗻𝗴 

For heavy operations, move logic to 𝗤𝘂𝗲𝘂𝗲𝗮𝗯𝗹𝗲 𝗔𝗽𝗲𝘅, 𝗕𝗮𝘁𝗰𝗵 𝗔𝗽𝗲𝘅, or 𝗣𝗹𝗮𝘁𝗳𝗼𝗿𝗺 𝗘𝘃𝗲𝗻𝘁𝘀 instead of synchronous execution.


𝟱. 𝗠𝗶𝗻𝗶𝗺𝗶𝘇𝗲 𝗥𝗲𝗰𝘂𝗿𝘀𝗶𝘃𝗲 𝗧𝗿𝗶𝗴𝗴𝗲𝗿𝘀 

Use static variables to prevent unwanted recursion and avoid unnecessary trigger executions.


𝗕𝗼𝗻𝘂𝘀 𝗧𝗶𝗽: Use the 𝗟𝗶𝗺𝗶𝘁𝘀.𝗴𝗲𝘁𝗖𝗽𝘂𝗧𝗶𝗺𝗲() method to track CPU usage in real-time and optimize accordingly.

No comments:

Post a Comment