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
Mhlangano KhumaloMhlangano Khumalo 

‘Apex CPU time limit'- I want to optimize my code...pls help.

My Webservice GET's a list of records in JSON format from another system, then updates to those specific records in Salesforce.
My data model: I have a master detail relationship between Account & Advance_Summary__c custom object. RC_Account_No__c is an external ID field that's unique on Account and Balance__c  is a custom currency field on Advance_Summary__c. We only need to update Balance__c,  the catch is if there is more that one Advance_Summary__c records related to an Account, we Only update the most recently created.

Below is the code.
 
/* Json string im getting looks like this.
[
	{
	"IDCUST": "RC-002394", //Mapped to RC_Account_No__c on Account
	"AMTBALDUEH": 1345.89 //Mapped to Balance__c on Advance_Summary__c
	},
	{
	"IDCUST": "RC-002408",
	"AMTBALDUEH": 133.33
	}
]
*/

public class CustomerStatsBatch 
{   
    @future(callout=true) 
    public static void executeThis() {
       
        Http h = new Http();    
        HttpRequest req = new HttpRequest();    
		
		//Calling the endpoint URL
        req.setEndpoint('http://crm.retal.com/SageERPAPI/api/CustomerStats'); 
 
        req.setMethod('GET');
    
        HttpResponse res = h.send(req);
    
        String rNf =res.getbody();
        String jsonString = '{"items": '+res.getbody()+'}'; 
		/* Above I format the JsonString so it looks like below
		{
		"items": [
				{
				"IDCUST": "RC-002394",
				"AMTBALDUEH": 1345.89
				},
				{
				"IDCUST": "RC-002408",
				"AMTBALDUEH": 133.33
				}
			    ]
		}
	     */
		
		//Deserialize it using apex class JSON2ApexCustomerStats
        JSON2ApexCustomerStats objResponseBody = 
					(JSON2ApexCustomerStats)JSON.deserialize(jsonString, JSON2ApexCustomerStats.class);

        List <Account> updateAcc = new List<Account>{};
        integer count = 0;
        
        List<String> rcNums = new List<String>{};
        List<Account> list2bUpdated = new List<Account>{};
        List<Advance_Summary__c> plswork = new List<Advance_Summary__c>{};
        
        //Load RC Numbers you're getting from json string so I can use them as an index
        for(JSON2ApexCustomerStats.items row: objResponseBody.items) {
            rcNums.add(row.IDCUST);
        }  
       
	    //The first query selects an account with aleast 1 child, the most recent if there more than 1
        for(Account rec : [select Id, RC_Account_No__c,
							(select id, Balance__c from Account.Balance__cr order by createddate desc limit 1) 
							from Account where RC_Account_No__c in: rcNums and Id In 
							(Select Advance_Summary__c from Advance_Summary__c) ]){
            for(JSON2ApexCustomerStats.items row: objResponseBody.items) {
            
                if(row.IDCUST == rec.RC_Account_No__c){
                    Account l = new Account();
                    l.id = rec.id;                   
                    list2bUpdated.add(l);
                    
                    Advance_Summary__c advSum = new Advance_Summary__c();
                    
                    //error in the line below if null;                         
                    advSum.id= rec.Advance_summary__r[0].id;
                    
                    advSum.Balance__c = row.AMTBALDUEH;
                    plswork.add(advSum);
                }
            }            
        }

        Database.update(list2bUpdated,false); 
        
        Database.update(plswork,false); 
        
        system.debug('list2bUpdated:'+ list2bUpdated);        
        system.debug('plswork:'+ plswork);
       
      }    
}
Your assistance will be appreciated and indicated as the best answer.
SandhyaSandhya (Salesforce Developers) 
Hi,

Below are some of the useful links which have some Best Practices to avoid Apex CPU Limit Exceeded.

https://help.salesforce.com/apex/HTViewSolution?id=000232681&language=en_US 
 
https://developer.salesforce.com/page/Apex_Code_Best_Practices
 
http://www.jitendrazaa.com/blog/salesforce/batch-apex-first-error-apex-cpu-time-limit-exceeded/
 
Hope this helps you!

If this helps you please mark it as solved.

Thanks and Regards
Sandhya