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
Raj DharsandiaRaj Dharsandia 

Heap limit getting hit

I have below for loop inside one apex method and here records i am passing as 3000 then it is hitting the heap limit and my code is not working as expected 

for(Integer i=0;i<recordsCount;i++){                
                Purchase_Request_Line_Item__c purchaseRequestLineItem = newPurchaseRequestLineItem.clone(false,true);
                String uniqueId= getUniqueId();
                Inventory_Item__c inventoryItemRecordReference = new Inventory_Item__c(PRLIExtID__c=uniqueId);
                purchaseRequestLineItem.Inventory_Item__r =inventoryItemRecordReference;
                SObject inventoryItemRecord = childObjRecord.clone(false, true);
                inventoryItemRecord.put('Name',inventoryItemRecord.get('Name')+'-'+String.valueOf(i)+' '+date.today().format());
                inventoryItemRecord.put('PRLIExtID__c',uniqueId);
                recordsToInsertInInventoryItem.add(inventoryItemRecord);
                recordsToInsertInPurchaseLine.add(purchaseRequestLineItem);
                if (math.mod(i, 1000) == 0) {
                    system.debug('Inside for: Heap size is ' + limits.getHeapSize() + ' enforced is ' + limits.getLimitHeapSize());
                }
            }
SwethaSwetha (Salesforce Developers) 
Troubleshooting appraoch to fix heap size error

1) Add the following debug method to the affected class:
void checkHeapSize(String tag) {
system.debug(tag + ': Heap size is ' + limits.getHeapSize() + ' enforced is ' + limits.getLimitHeapSize());
}

2a) Call the method at various points in the code using a "tag" parameter so that you know where it's called in the code. For example: checkHeapSize('constructor1');

2b) In order to check the heap limit, put the check in the loop and then run the check every 1000th iteration. This is done by adding a local variable called "i" (i.e. "integer i;"), increment it for each iteration, and then running the following code: if (math.mod(i, 1000) == 0) } { call the method }.

3) Review the debug logs to find the heap size to see if it's exceeding the limit. For issues with scheduled batches, testing in the Developer Console will run code synchronously and show the limit as 6 MB but the heap size limit for scheduled batches is the asynchronous limit of 12MB.

4) If heap size doesn't exceed the limit, repeat steps 1-3. If the limit is exceeded, the debug logs should point out the problematic section of code that will need to be fixed.

Example Problem Code
retryIds = new Set<String>();
for(Process_Error__c pe : [SELECT Id, Asset_Maintenance__c, AssetId__c, Error_Messages__c, No_of_Retries__c, Is_Successful__c FROM Process_Error__c WHERE Is_Successful__c = FALSE AND Max_Retries_Reached__c = FALSE]){
ProcessErrorMap.put(pe.AssetId__c, pe);
if (pe.Asset_Maintenance__c != null) {
retryIds.add(pe.Asset_Maintenance__c);
}
}


To troubleshoot the code above, the checkHeapSize method can be called every 1000th iteration (per step 2b) in order to show the heap size growing and exceeding the limit. The problem above was that many objects were being added to a variable, in this case retryIds was adding objects and its size was growing too large for the heap limit. The heap size will change depending on the size of the objects so this code would need to be changed to avoid hitting the heap size limit when many records are processed.

You may follow below best practices to avoid running into Apex heap size limit:

- Don't use class level variables to store a large amounts of data.
- Utilize SOQL For Loops to iterate and process data from large queries.
- Construct methods and loops that allow variables to go out of scope as soon as they are no longer needed.

Please refer the following link which discusses on different strategies to manage the heap size.

>>http://blog.jeffdouglas.com/2010/08/16/managing-the-heap-in-salesforce-com/

>>https://success.salesforce.com/questionDetail?qid=a1X30000000ddWJEAY